 
package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.rca.entity.*;
import com.zdkj.subway.rca.enums.SwCkClearRuleConstans;
import com.zdkj.subway.rca.mapper.SwCkClearDetailMapper;
import com.zdkj.subway.rca.service.*;
import com.zdkj.subway.rca.util.MyBeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 清分及划账记录
 *
 * @author stw
 * @date 2020-11-30 18:52:08
 */
@Service
public class SwCkClearDetailServiceImpl extends ServiceImpl<SwCkClearDetailMapper, SwCkClearDetail> implements SwCkClearDetailService {
	private static final Logger log = LoggerFactory.getLogger(SwCkClearDetailServiceImpl.class);

    @Autowired
    private SwCkSysCleaningConsTicketService swCkSysCleaningConsTicketService;
	@Autowired
    private SwCkClearRulesService swCkClearRuleService;
    @Autowired
    private SwCkClearRulesLineService swCkClearRulesLineService;
    @Autowired
    private SwCkClearAccountDetailService swCkClearAccountDetailService;
    @Autowired
    private SwCkClearingReportOnewayTicketService swCkClearingReportOnewayTicketService;
    @Autowired
    private SwCkClearingReportQrService swCkClearingReportQrService;
    @Autowired
    private SwCkClearingAccountRepportFaceService swCkClearingAccountRepportFaceService;
    @Autowired
    private SwCkClearingTransferDiffReasonService swCkClearingTransferDiffReasonService;
    @Autowired
    private SwCkDiffAfterClearService swCkDiffAfterClearService;
    @Autowired
    private SwCkBomSmallPaymentService swCkBomSmallPaymentService;
    @Autowired
    private SwCkClearDailyTicketReportService swCkClearDailyTicketReportService; 
    @Autowired
    private ViewCkOperatorsTicketRevenueClearService viewCkOperatorsTicketRevenueClearService;

    //按月清分纪念票、日票和计次票(暂不处理)金额
    /*
     * 纪念票计算规则：
     * 1.A=所有运营商收入日报表的对应票种的售卖收入合计金额
     * 2. B
     *   2.1 西安地铁以及西咸获取各线路对应的清分比例 
     *   2.2 机场和西安中铁获得运营商的清分比例
     * 3. C只是显示
     *   3.1西安地铁以及西咸获取各线路对应的清分清分次数
     *   3.2 机场和西安中铁获得运营商的清分次数
     * 4.清分结果
     *   A*B 
     * 日票计算规则同纪念票，区别在于：
     * 9号线，14号线售卖收入取日表日票的现金部分
              西安地铁，西咸取合计部分，西咸的放到代售西咸款内， 对应的代售清分结果为0，但对应运营商线路显示清分结果。
              代收9和14号线的售卖收入为日报表中的电子部分。
              线路百分比是当前线路/所有运营商的线路合计值。

     *     
     * 
     */
	 @Override
     public Boolean generateSpecialTicketsSwCkClearDetail(String startDate,String endDate,List<String> lstClearRules){
    	  
    	boolean isContainDaily = lstClearRules.contains(SwCkClearRuleConstans.CLEAR_RULE_DAILY_TICKET);
    	boolean isContainSouvenir = lstClearRules.contains(SwCkClearRuleConstans.CLEAR_RULE_SOUVENIR_TICKET);
    	//1.根据日期范围和清分规则，从清分规则表内查找对应票种的清分比例,  value:具体比例
    	// String key = datas.getClearRules()+","+datas.getSubClearRules()+","+datas.getOperators()+","+dataDetail.getLineCode();
    	Map<String,String> mapLineClearRule = swCkClearRuleService.selectRulesDetailsMapByDate(startDate, endDate) ;
    	
       BigDecimal lDailyTicketsAll = new BigDecimal("0");//日票总的售卖收入
       BigDecimal lSunverTicketAll = new BigDecimal("0");//纪念票总的售卖收入
 	   Map<String,BigDecimal> mapReportLineDailyTickets = new  HashMap<>();//每条线路的日票售卖收入
 	   Map<String,BigDecimal> mapReportLineSunverTicket = new  HashMap<>();//每条线路的纪念票售卖收入
 	   
 	   Map<String,BigDecimal> mapAccLineDailyTickets = new  HashMap<>();//接口每线路的日票售卖收入
	   Map<String,BigDecimal> mapAccLineSunverTicket = new  HashMap<>();//接口每条线路的纪念票售卖收入
	   
	   PigxUser user = SecurityUtils.getUser();
	   List<Map<String,String>> lineMap = swCkBomSmallPaymentService.selectLineMap();
	   
	   //从ACC接口中获取对应的清分次数数量
	   List<Map<String,Object>> lstDailyAll = swCkSysCleaningConsTicketService.getAccDailySpecialTicketMap(startDate, endDate);//日票的各个线路的金额
	   List<Map<String,Object>> lstSunivenirAll = swCkSysCleaningConsTicketService.getAccSouvenirSpecialTicketMap(startDate, endDate);//纪念票的各个线路的金额
 	  
	  //从地铁日报表中获取对应票种的售卖收入（所有运营商的合计值）
       List<Map<String,Object>> dailyReportDataList = new ArrayList<>();
       List<Map<String,Object>> dailyReportDataListInit = this.baseMapper.selectSpecialTicketsDailyReportDataList(startDate,endDate);//西安地铁
       List<Map<String,Object>> dailyReportAirDataList = this.baseMapper.selectSpecialTicketsOtherOperatorsDailyReportDataList(startDate,endDate);  //机场线
       List<Map<String,Object>> dailyReport9DataList = this.baseMapper.selectSpecialTicketsOtherXaztOperatorsDailyReportDataList(startDate,endDate);//9号线
       if(CollectionUtil.isNotEmpty(dailyReportDataListInit) && ObjectUtil.isNotEmpty(dailyReportDataListInit.get(0).get("lineCode"))){
           dailyReportDataList.addAll(dailyReportDataListInit);
       }
       if(CollectionUtil.isNotEmpty(dailyReportAirDataList) && ObjectUtil.isNotEmpty(dailyReportAirDataList.get(0).get("lineCode"))){
           dailyReportDataList.addAll(dailyReportAirDataList);
       }
       if(CollectionUtil.isNotEmpty(dailyReport9DataList) && ObjectUtil.isNotEmpty(dailyReport9DataList.get(0).get("lineCode"))){
           dailyReportDataList.addAll(dailyReport9DataList);
       }
       /*TODO  stream处理求和 
        *  日票：D2:待清分金额 D21：电子             D22： 现金
        *  纪念票票：D3:待清分金额      D31：电子        D32 现金
        *  1. D2，D21相加求和后赋值给   lDailyTicketsAll  //从日报表dailyReportDataList
        *  2. D3相加求和后赋值给   lSunverTicketAll  //从日报表dailyReportDataList
        *  3. 以Linecode为主键遍历，从日报表dailyReportDataList 中获取当前线路的D2，D21，D3分别赋值给
        *     mapReportLineDailyTickets.put(lineCode,D2);
        *     mapReportLineDailyTickets.put(lineCode+"D21",D21);
        *     mapReportLineDailyTickets.put(lineCode+"D22",D22);
        *     mapReportLineSunverTicket.put(lineCode,D3);
        *     mapReportLineSunverTicket.put(lineCode+"D31",D31);
        *     mapReportLineSunverTicket.put(lineCode+"D32",D32);
        *  4. 以Linecode为主键遍历，获从Acc接口中获取当前线路的日票纪念票money赋值给
        *     mapAccLineDailyTickets.put(lineCode,D2); //遍历lstDailyAll，然后放Map中
        *     mapAccLineSunverTicket.put(lineCode,D3);  //遍历lstSunivenirAll，然后放Map中
        *
       */

        //D2，D21相加求和后赋值给   lDailyTicketsAll
         if(CollectionUtil.isNotEmpty(dailyReportDataList) && ObjectUtil.isNotEmpty(dailyReportDataList.get(0).get("lineCode"))){

             BigDecimal d21 = dailyReportDataList.stream().map(m -> new BigDecimal(String.valueOf(m.get("D21")))).reduce(BigDecimal.ZERO,BigDecimal::add);
             BigDecimal d22 = dailyReportDataList.stream().map(m -> new BigDecimal(String.valueOf(m.get("D22")))).reduce(BigDecimal.ZERO,BigDecimal::add);
             lDailyTicketsAll = d21.add(d22);

             //D3相加求和后赋值给   lSunverTicketAll 改为同日票处理方式
             //lSunverTicketAll = dailyReportDataList.stream().mapToLong(m -> (long) m.get("D3")).sum();
             BigDecimal d31 = dailyReportDataList.stream().map(m -> new BigDecimal(String.valueOf(m.get("D31")))).reduce(BigDecimal.ZERO,BigDecimal::add);
             BigDecimal d32 = dailyReportDataList.stream().map(m -> new BigDecimal(String.valueOf(m.get("D32")))).reduce(BigDecimal.ZERO,BigDecimal::add);
             lSunverTicketAll = d31.add(d32);

             //以Linecode为主键遍历，从日报表dailyReportDataList 中获取当前线路的D2，D21，D3分别赋值给
             Map<String, List<Map<String, Object>>> lineCodeMap = dailyReportDataList.stream().collect(Collectors.groupingBy(m -> m.get("lineCode").toString(), Collectors.toList()));
             Set<String> keySet = lineCodeMap.keySet();
             for (String lineCode : keySet) {
                 List<Map<String, Object>> mapsList = lineCodeMap.get(lineCode);
                 // todo 确认是否用bigdecimal
                 BigDecimal lineD2 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("D2")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                 BigDecimal lineD21 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("D21")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                 BigDecimal lineD22 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("D22")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                 BigDecimal lineD3 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("D3")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                 BigDecimal lineD31 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("D31")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                 BigDecimal lineD32 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("D32")))).reduce(BigDecimal.ZERO,BigDecimal::add);
//             Long lineD2 = mapsList.stream().mapToLong(m -> (long) m.get("D2")).sum();
//             Long lineD21 = mapsList.stream().mapToLong(m -> (long) m.get("D21")).sum();
//             Long lineD3 = mapsList.stream().mapToLong(m -> (long) m.get("D3")).sum();
                 mapReportLineDailyTickets.put(lineCode,lineD2);
                 mapReportLineDailyTickets.put(lineCode+"D21",lineD21);
                 mapReportLineDailyTickets.put(lineCode+"D22",lineD22);
                 mapReportLineSunverTicket.put(lineCode,lineD3);
                 mapReportLineSunverTicket.put(lineCode+"D31",lineD31);
                 mapReportLineSunverTicket.put(lineCode+"D32",lineD32);
             }
         }

         if(CollectionUtil.isNotEmpty(lstDailyAll) && ObjectUtil.isNotEmpty(lstDailyAll.get(0).get("lineCode"))){

             //以Linecode为主键遍历，获从Acc接口中获取当前线路的日票纪念票money赋值给
             Map<String, List<Map<String, Object>>> lstDailyMap = lstDailyAll.stream().collect(Collectors.groupingBy(m -> m.get("lineCode").toString(), Collectors.toList()));
             Set<String> keySet2 = lstDailyMap.keySet();
             for (String lineCode : keySet2) {
                 List<Map<String, Object>> mapsList = lstDailyMap.get(lineCode);
                 // todo 确认是否用bigdecimal
                 BigDecimal lineD2 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("cleanNumber")))).reduce(BigDecimal.ZERO,BigDecimal::add);
//             Long lineD2 = mapsList.stream().mapToLong(m -> (long) m.get("D2")).sum();
                 mapAccLineDailyTickets.put(lineCode,lineD2);
             }
         }

         if(CollectionUtil.isNotEmpty(lstSunivenirAll) && ObjectUtil.isNotEmpty(lstSunivenirAll.get(0).get("lineCode"))){

             Map<String, List<Map<String, Object>>> lstSunivenirMap = lstSunivenirAll.stream().collect(Collectors.groupingBy(m -> m.get("lineCode").toString(), Collectors.toList()));
             Set<String> keySet3 = lstSunivenirMap.keySet();
             for (String lineCode : keySet3) {
                 List<Map<String, Object>> mapsList = lstSunivenirMap.get(lineCode);
                 // todo 确认是否用bigdecimal
                 BigDecimal lineD3 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("cleanNumber")))).reduce(BigDecimal.ZERO,BigDecimal::add);
//             Long lineD3 = mapsList.stream().mapToLong(m -> (long) m.get("D3")).sum();
                 mapAccLineSunverTicket.put(lineCode,lineD3);
             }
         }


         //获取时间段内的西安地铁和其他运营商的线路列表
        List<String> listLine = this.baseMapper.selectLineList(startDate,endDate); 
        
        if (listLine != null && !listLine.isEmpty()) {
        	List<SwCkClearDailyTicketReport>  listSouvenirAdd = new ArrayList();
        	List<SwCkClearDailyTicketReport>  listDailyAdd = new ArrayList();
        	 for (String lineCode : listLine) {
                 String serviceId = swCkSysCleaningConsTicketService.getServiceOrgByLine(lineCode).get("serviceId");
                 //单条线路的售卖数量
                 BigDecimal D2 = getData(mapReportLineDailyTickets.get(lineCode));//日票
                 BigDecimal D21 = getData(mapReportLineDailyTickets.get(lineCode+"D21"));//日票 电子
                 BigDecimal D22 = getData(mapReportLineDailyTickets.get(lineCode+"D22"));//日票 现金
                 BigDecimal D3 = getData(mapReportLineSunverTicket.get(lineCode));//纪念票
                 BigDecimal D31 = getData(mapReportLineDailyTickets.get(lineCode+"D31"));//日票 电子
                 BigDecimal D32 = getData(mapReportLineDailyTickets.get(lineCode+"D32"));//日票 现金
                 
                 
                 //清分比例             
                 String ruleKeyDaily = SwCkClearRuleConstans.CLEAR_RULE_DAILY_TICKET+","+"1"+","+serviceId+","+lineCode;
                 String ruleKeySunivenir = SwCkClearRuleConstans.CLEAR_RULE_SOUVENIR_TICKET+","+"1"+","+serviceId+","+lineCode;
                 Double scaleDaily = Double.valueOf(getData2(mapLineClearRule.get(ruleKeyDaily)));//日票清分比例
                 Double scaleSunivenir = Double.valueOf(getData2(mapLineClearRule.get(ruleKeySunivenir))); //纪念票清分比例
                		 
  			     
                 //清分次数 
                 BigDecimal lDailyLine = getData(mapAccLineDailyTickets.get(lineCode));
                 BigDecimal lSunivenirLine = getData(mapAccLineSunverTicket.get(lineCode));

                 BigDecimal decimal100 = new BigDecimal("100");
                 //清分结果
                 BigDecimal lDailyClearValue = (lDailyTicketsAll.multiply(new BigDecimal(String.valueOf(scaleDaily))).divide(decimal100)).setScale(5,BigDecimal.ROUND_HALF_UP);
                 BigDecimal lSunivenirClearValue = (lSunverTicketAll.multiply(new BigDecimal(String.valueOf(scaleSunivenir))).divide(decimal100)).setScale(5,BigDecimal.ROUND_HALF_UP);

                if(isContainSouvenir){
                	 //组织纪念票库表数据  sw_ck_clear_souvenir_ticket_report
              	    SwCkClearDailyTicketReport souvenirTicket = new SwCkClearDailyTicketReport();
              	    souvenirTicket.setBeginTime(LocalDate.parse(startDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
              	    souvenirTicket.setEndTime(LocalDate.parse(endDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    souvenirTicket.setLineCode(lineCode);//
                    souvenirTicket.setDelFlag("0");
                    //TODO，根据日期范围、线路判断是否存在，如果存在更新，不存在插入
                    QueryWrapper<SwCkClearDailyTicketReport> query = Wrappers.query(souvenirTicket);
                    SwCkClearDailyTicketReport report = swCkClearDailyTicketReportService.getOne(query);
                    if(ObjectUtil.isNotEmpty(report)){
                        souvenirTicket.setId(report.getId());
                        BeanUtils.copyProperties(report,souvenirTicket);
                        souvenirTicket.setUpdateTime(LocalDateTime.now());
                    }
                    souvenirTicket.setOperators(serviceId);
                    souvenirTicket.setCashSouvenir(D32);
                    souvenirTicket.setEleSouvenir(D31);
                    if(serviceId.equals(SwCkClearRuleConstans.SERVICE_ID_XIXIAN)){
                    	souvenirTicket.setSaleIncomeSouvenir(new BigDecimal("0")); //售卖收入,西咸车站设置为0
                    }else{
                    	souvenirTicket.setSaleIncomeSouvenir(D3); //售卖收入
                    }
                    
                    souvenirTicket.setClearAmountSouvenir(lSunivenirLine);//清分次数
                    souvenirTicket.setClearScaleSouvenir(String.valueOf(scaleSunivenir));//清分比例
                    souvenirTicket.setClearMoneySouvenir(lSunivenirClearValue);//清分结果
                    souvenirTicket.setDeptId(user.getDeptId());
                    souvenirTicket.setCreatorId(user.getId());
                    souvenirTicket.setCreatorName(user.getNikeName());
                    listSouvenirAdd.add(souvenirTicket);

                } 
                
                if(isContainDaily){
                	//组织日票库表数据  sw_ck_clear_daily_ticket_report
                    //如果是西咸的线路，日报表的售卖收入置为0，否则其他正常取
                   if(serviceId.equals(SwCkClearRuleConstans.SERVICE_ID_XIXIAN)){
                  	   D2 = new BigDecimal(0);
                   }
                   SwCkClearDailyTicketReport dailyTicket = new SwCkClearDailyTicketReport();
                   dailyTicket.setBeginTime(LocalDate.parse(startDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                   dailyTicket.setEndTime(LocalDate.parse(endDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                   dailyTicket.setLineCode(lineCode);
                   dailyTicket.setDelFlag("0");
                    //TODO，根据日期范围、线路判断是否存在，如果存在更新，不存在插入
                    QueryWrapper<SwCkClearDailyTicketReport> query = Wrappers.query(dailyTicket);
                    SwCkClearDailyTicketReport report = swCkClearDailyTicketReportService.getOne(query);
                    if(ObjectUtil.isNotEmpty(report)){
                        dailyTicket.setId(report.getId());
                        BeanUtils.copyProperties(report,dailyTicket);
                        dailyTicket.setUpdateTime(LocalDateTime.now());
                    }
                    
                    dailyTicket.setOperators(serviceId);
                    dailyTicket.setOperatorsname(swCkSysCleaningConsTicketService.getServiceOrgByLine(lineCode).get("serviceName"));
                    dailyTicket.setLineName(getLineName(lineMap,lineCode));// 需要根据线路编号转换成线路名称
                    dailyTicket.setCashDaily(D22);
                    dailyTicket.setEleDaily(D21);
                    if(serviceId.equals(SwCkClearRuleConstans.SERVICE_ID_XIXIAN)){
                    	dailyTicket.setSaleIncome(new BigDecimal("0")); //售卖收入,西咸车站设置为0
                    }else{
                    	dailyTicket.setSaleIncome(D2); //售卖收入
                    }
                    
                    dailyTicket.setClearScale(String.valueOf(scaleDaily));//清分比例
                    dailyTicket.setClearAmount(lDailyLine);//清分次数
                    dailyTicket.setClearMoney(lDailyClearValue);//清分结果
                    dailyTicket.setDeptId(user.getDeptId());
                    dailyTicket.setCreatorId(user.getId());
                    dailyTicket.setCreatorName(user.getNikeName());
                    listDailyAdd.add(dailyTicket);
                }
                
                
         	     
        	 } //for 循环线路结束
        	
        	 if(isContainDaily){
	        	 //追加代售线路的日报表的金额设置代收,清分结果设置为0，清分比例设置为0
	
	        	 //1.1 代收14号线机场段款
	        	//单条线路的售卖数量
                 //if(CollectionUtil.isNotEmpty(mapReportLineDailyTickets)){
        		    /*
                     BigDecimal D2 = getData(mapReportLineDailyTickets.get("54D21"));//日票电子
                     String ruleKeyDaily = SwCkClearRuleConstans.CLEAR_RULE_DAILY_TICKET+","+"1"+","+SwCkClearRuleConstans.SERVICE_ID_AIR+",54";
                     Double scaleDaily = Double.valueOf(getData2(mapLineClearRule.get(ruleKeyDaily)));//日票清分比例
                     */
					 BigDecimal D2 = getData(mapReportLineDailyTickets.get("54D21"));//日票电子
        		     Double scaleDaily = 0.00;
                     BigDecimal lDailyClearValue = new BigDecimal("0.00");

                     String serviceName="西安地铁";
                     String serviceExtraId = SwCkClearRuleConstans.SERVICE_ID_XADT;
                     SwCkClearDailyTicketReport swCkClearDailyTicketReport14 = calcuteCollectionDailyReport(user,startDate,endDate,"154","代收14号线机场段",serviceExtraId,serviceName,D2,String.valueOf(scaleDaily),lDailyClearValue,true);
                     //1.2 代收9号线款
                     /*
                     D2 = getData(mapReportLineDailyTickets.get("9D21"));//日票电子
                     ruleKeyDaily = SwCkClearRuleConstans.CLEAR_RULE_DAILY_TICKET+","+"1"+","+SwCkClearRuleConstans.SERVICE_ID_XAZT+",9";
                     scaleDaily = Double.valueOf(getData2(mapLineClearRule.get(ruleKeyDaily)));//日票清分比例
                     */
					 D2 = getData(mapReportLineDailyTickets.get("9D21"));//日票电子
                     SwCkClearDailyTicketReport swCkClearDailyTicketReport9 = calcuteCollectionDailyReport(user,startDate,endDate,"1149","代收9号线款",serviceExtraId,serviceName,D2,String.valueOf(scaleDaily),lDailyClearValue,true);

                     //2.3 代收西咸款
                     /*
                     D2 = getData(mapReportLineDailyTickets.get("71")).add(getData(mapReportLineDailyTickets.get("72")));//两个二期线路日票（现金+电子）合计金额
                     ruleKeyDaily = SwCkClearRuleConstans.CLEAR_RULE_DAILY_TICKET+","+"1"+","+SwCkClearRuleConstans.SERVICE_ID_XIXIAN+",71";
                     scaleDaily = Double.valueOf(getData2(mapLineClearRule.get(ruleKeyDaily)));//日票清分比例
                     */
					 D2 = getData(mapReportLineDailyTickets.get("71")).add(getData(mapReportLineDailyTickets.get("72")));//两个二期线路日票（现金+电子）合计金额
                     SwCkClearDailyTicketReport swCkClearDailyTicketReport71 = calcuteCollectionDailyReport(user,startDate,endDate,"1171","代收西咸款",serviceExtraId,serviceName,D2,String.valueOf(scaleDaily),lDailyClearValue,true);

                     //TODO，根据日期范围、线路判断是否存在，如果存在更新，不存在插入
                     listDailyAdd.add(swCkClearDailyTicketReport9);
                     listDailyAdd.add(swCkClearDailyTicketReport14);
                     listDailyAdd.add(swCkClearDailyTicketReport71);
                 //}
        	 }
        	 if(isContainSouvenir){
	        	 //追加代售线路的日报表的金额设置代收,清分结果设置为0 	
	        	 //1.1 代收14号线机场段款
	        	//单条线路的售卖数量
                // if(CollectionUtil.isNotEmpty(mapReportLineSunverTicket)){
                     /*
        		     BigDecimal D3 = getData(mapReportLineSunverTicket.get("54D31"));//纪念票电子
                     String ruleKeyDaily = SwCkClearRuleConstans.CLEAR_RULE_SOUVENIR_TICKET+","+"1"+","+SwCkClearRuleConstans.SERVICE_ID_AIR+",54";
                     Double scaleDaily = Double.valueOf(getData2(mapLineClearRule.get(ruleKeyDaily)));//纪念票清分比例
                     */
					 BigDecimal D3 = getData(mapReportLineSunverTicket.get("54D31"));//纪念票电子
        		     Double scaleDaily = 0.00;
                     BigDecimal lDailyClearValue = new BigDecimal("0.00");

                     String serviceName="西安地铁";
                     String serviceExtraId = SwCkClearRuleConstans.SERVICE_ID_XADT;
                     SwCkClearDailyTicketReport swCkClearDailyTicketReport14 = calcuteCollectionDailyReport(user,startDate,endDate,"154","代收14号线机场段",serviceExtraId,serviceName,D3,String.valueOf(scaleDaily),lDailyClearValue,false);
                     //1.2 代收9号线款
                     /*
                     D3 = getData(mapReportLineSunverTicket.get("9D31"));//纪念票电子
                     ruleKeyDaily = SwCkClearRuleConstans.CLEAR_RULE_SOUVENIR_TICKET+","+"1"+","+SwCkClearRuleConstans.SERVICE_ID_XAZT+",9";
                     scaleDaily = Double.valueOf(getData2(mapLineClearRule.get(ruleKeyDaily)));//纪念票清分比例
                     */
					 D3 = getData(mapReportLineSunverTicket.get("9D31"));//纪念票电子
                     SwCkClearDailyTicketReport swCkClearDailyTicketReport9 = calcuteCollectionDailyReport(user,startDate,endDate,"1149","代收9号线款",serviceExtraId,serviceName,D3,String.valueOf(scaleDaily),lDailyClearValue,false);

                     //2.3 代收西咸款
                     /*
                     D3 = getData(mapReportLineSunverTicket.get("71")).add(getData(mapReportLineSunverTicket.get("72")));//两个二期线路纪念票（现金+电子）合计金额
                     ruleKeyDaily = SwCkClearRuleConstans.CLEAR_RULE_SOUVENIR_TICKET+","+"1"+","+SwCkClearRuleConstans.SERVICE_ID_XIXIAN+",71";
                     scaleDaily = Double.valueOf(getData2(mapLineClearRule.get(ruleKeyDaily)));//纪念票清分比例
                     */
					 D3 = getData(mapReportLineSunverTicket.get("71")).add(getData(mapReportLineSunverTicket.get("72")));//两个二期线路纪念票（现金+电子）合计金额
                     SwCkClearDailyTicketReport swCkClearDailyTicketReport71 = calcuteCollectionDailyReport(user,startDate,endDate,"1171","代收西咸款",serviceExtraId,serviceName,D3,String.valueOf(scaleDaily),lDailyClearValue,false);

                     //TODO，根据日期范围、线路判断是否存在，如果存在更新，不存在插入
                     listDailyAdd.add(swCkClearDailyTicketReport9);
                     listDailyAdd.add(swCkClearDailyTicketReport14);
                     listDailyAdd.add(swCkClearDailyTicketReport71);
                // }
        	 }
          
         if(listSouvenirAdd!=null && !listSouvenirAdd.isEmpty()){
        	 // TODO 调用纪念票的保存方法。
        	 swCkClearDailyTicketReportService.saveOrUpdateBatch(listSouvenirAdd);
          }	
          if(listDailyAdd!=null && !listDailyAdd.isEmpty()){
         	 // TODO 调用日票的保存方法。
              swCkClearDailyTicketReportService.saveOrUpdateBatch(listDailyAdd);
           }	
        }
    	return false;
    	
    }
    //组织代收的日票数据
    private SwCkClearDailyTicketReport calcuteCollectionDailyReport(PigxUser user,String startDate,String endDate,String lineCode,String lineName,String serviceId,String serviceName,BigDecimal D2,String scaleDaily,BigDecimal lDailyClearValue,boolean isDailyReport){
    	SwCkClearDailyTicketReport dailyTicket = new SwCkClearDailyTicketReport();
        dailyTicket.setBeginTime(LocalDate.parse(startDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        dailyTicket.setEndTime(LocalDate.parse(endDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        dailyTicket.setLineCode(lineCode);//
        //TODO，根据日期范围、线路判断是否存在，如果存在更新，不存在插入
        QueryWrapper<SwCkClearDailyTicketReport> query = Wrappers.query(dailyTicket);
        SwCkClearDailyTicketReport report = swCkClearDailyTicketReportService.getOne(query);
        if(ObjectUtil.isNotEmpty(report)){
            dailyTicket.setId(report.getId());
            BeanUtils.copyProperties(report,dailyTicket);
            dailyTicket.setUpdateTime(LocalDateTime.now());
        }
        dailyTicket.setOperatorsname(serviceName);
        dailyTicket.setOperators(serviceId);
        dailyTicket.setLineName(lineName);//
        dailyTicket.setDelFlag("0");
        if(isDailyReport){
        	dailyTicket.setSaleIncome(D2); //售卖收入
            dailyTicket.setClearScale(scaleDaily);//清分比例
            dailyTicket.setClearMoney(lDailyClearValue);//清分结果
        }else{
        	dailyTicket.setSaleIncomeSouvenir(D2); //售卖收入
            dailyTicket.setClearScaleSouvenir(scaleDaily);//清分比例
            dailyTicket.setClearMoneySouvenir(lDailyClearValue);//清分结果
        }
        
        dailyTicket.setDeptId(user.getDeptId());
        dailyTicket.setCreatorId(user.getId());
        dailyTicket.setCreatorName(user.getNikeName());
        return dailyTicket;


    }
  //正常清分数据操作，实际对应人工协议清分比例的计算
   @Override
   @Transactional(rollbackFor = Exception.class)
   public Boolean generateSwCkClearDetail(String startDate, String endDate) {

	   log.info("正常清分---系统自动计算开始于:{}", LocalDateTime.now());
       boolean flag = false;
       //获取时间段内的西安地铁和其他运营商的线路列表
       List<String> listLine = this.baseMapper.selectLineList(startDate,endDate);
       if (listLine != null && !listLine.isEmpty()) {
    	   
    	// String key = datas.getClearRules()+","+datas.getSubClearRules()+","+datas.getOperators()+","+dataDetail.getLineCode();
       	   Map<String,String> mapLineClearRule = swCkClearRuleService.selectRulesDetailsMapByDate(startDate, endDate) ;
           BigDecimal sumB0 = new BigDecimal("0");
           BigDecimal sumC6 = new BigDecimal("0");
           BigDecimal sumI = new BigDecimal("0");
           BigDecimal sumXianSubwayI = new BigDecimal("0");

           BigDecimal sumE1 = new BigDecimal("0");
           BigDecimal sumE2 = new BigDecimal("0");

           BigDecimal sumF1 = new BigDecimal("0");
           BigDecimal sumF2 = new BigDecimal("0");

           BigDecimal sumH1 = new BigDecimal("0");
           BigDecimal sumH2 = new BigDecimal("0");
           
           BigDecimal sumD3 = new BigDecimal("0");//所有线路的纪念票合计
           BigDecimal sumD8 = new BigDecimal("0");//所有线路的纪念票系统清分合计

		   BigDecimal sumG10 = new BigDecimal("0");//所有线路的应急及互联互通金额合计
		   BigDecimal sumG0 = new BigDecimal("0");//所有线路二维码消费金额
		   BigDecimal sumGn = new BigDecimal("0");//所有线路二维码系统清分金额
		   
           //存放临时变量到内存中，减少SQL查询
          
           Map<String,BigDecimal> mapB1 = new HashMap();
           Map<String,BigDecimal> mapB2 = new HashMap();
           Map<String,BigDecimal> mapB3 = new HashMap();
           Map<String,BigDecimal> mapB4 = new HashMap();
           Map<String,BigDecimal> mapB5 = new HashMap();
           Map<String,BigDecimal> mapB6 = new HashMap();
           Map<String,BigDecimal> mapC1 =new HashMap();
           Map<String,BigDecimal> mapC2 =new HashMap();
           Map<String,BigDecimal> mapC3 =new HashMap();
           Map<String,BigDecimal> mapC4 =new HashMap();
           Map<String,BigDecimal> mapC5 =new HashMap();
		   //Map<String,BigDecimal> mapC61 =new HashMap();
          
           Map<String,BigDecimal> mapD1 =new HashMap();
           Map<String,BigDecimal> mapD2 =new HashMap();
           Map<String,BigDecimal> mapD3 =new HashMap();
           Map<String,BigDecimal> mapD8 =new HashMap();
           Map<String,BigDecimal> mapE1 =new HashMap();
           Map<String,BigDecimal> mapE2 =new HashMap();
           Map<String,BigDecimal> mapF1 =new HashMap();
           Map<String,BigDecimal> mapF2 =new HashMap();
           Map<String,BigDecimal> mapG4 = new HashMap();
           Map<String,BigDecimal> mapG5 = new HashMap();
           Map<String,BigDecimal> mapG6 = new HashMap();
           Map<String,BigDecimal> mapG7 = new HashMap();
		   Map<String,BigDecimal> mapG9 = new HashMap();
		   Map<String,BigDecimal> mapG10 = new HashMap();
           Map<String,BigDecimal> mapH2 = new HashMap();
           Map<String,Map<String,Object>> mapDailyReport = new HashMap();
           Map<String,String> mapServiceId = new HashMap();

		   List<Map<String,Object>> listSystemClearData = swCkSysCleaningConsTicketService.getE2F2(startDate,endDate);

           //计算合计值
           for (String lineCode : listLine) {
               //各指标定义,参见word文档,下同
			    //根据线路ID，返回不同日报表的数据。目前包括西安地铁、西咸、西安中铁和机场城际四个日报表
                //从线路表查找所属的serviceid
			   String serviceId = swCkSysCleaningConsTicketService.getServiceOrgByLine(lineCode).get("serviceId");
               Map<String,Object> dailyReportMap = swCkSysCleaningConsTicketService.getDailyReportMap(startDate,endDate,lineCode,serviceId);
               BigDecimal B1 = new BigDecimal(String.valueOf(dailyReportMap.get("B1")));
               BigDecimal B2 = new BigDecimal(String.valueOf(dailyReportMap.get("B2")));
               BigDecimal B3 = swCkSysCleaningConsTicketService.getB3(startDate,endDate,lineCode);
               BigDecimal B4 = swCkSysCleaningConsTicketService.getB4(startDate,endDate,lineCode);
               BigDecimal B5 = swCkSysCleaningConsTicketService.getB5(startDate,endDate,lineCode);
               Long B6 = swCkSysCleaningConsTicketService.getB6(startDate,endDate,lineCode);
               //（退款和抵消记成负数后再求和）B5,和B6  20210811
               //Long B0 = B1 + B2 + B3 + B4- B5 - B6;
               BigDecimal B0 = B1.add(B2).add(B3).add(B4).subtract(B5).subtract(new BigDecimal(String.valueOf(B6)));

               BigDecimal C1 = swCkSysCleaningConsTicketService.getC1(startDate,endDate,lineCode);
               BigDecimal C2 = swCkSysCleaningConsTicketService.getC2(startDate,endDate,lineCode);
               BigDecimal C3 = swCkSysCleaningConsTicketService.getC3(startDate,endDate,lineCode);
               BigDecimal C4 = swCkSysCleaningConsTicketService.getC4(startDate,endDate,lineCode);
               BigDecimal C5 = swCkSysCleaningConsTicketService.getC5(startDate,endDate,lineCode);
               //BigDecimal C61 = swCkSysCleaningConsTicketService.getC61(startDate,endDate,lineCode);
               BigDecimal C6 = C1.add(C2).add(C3).add(C4).add(C5);//.add(C61);  先不加C61试试,否则和10号的对不上    2021-11-21
			   


               BigDecimal D1 = new BigDecimal(String.valueOf(dailyReportMap.get("D1")));
               BigDecimal D2 = new BigDecimal(String.valueOf(dailyReportMap.get("D2")));
               BigDecimal D3 = new BigDecimal(String.valueOf(dailyReportMap.get("D3")));
               //Long D8 = swCkSysCleaningConsTicketService.getD8(startDate,endDate,lineCode);  纪念票的清分结果不在这里处理


               BigDecimal E1 = swCkSysCleaningConsTicketService.getE1(startDate,endDate,lineCode);
               BigDecimal E2 = getSystemClearLongValueByLineCode(listSystemClearData,lineCode,"cat");//dailyReportMap.get("E2"); 改为从系统清分获取
               BigDecimal F1 = swCkSysCleaningConsTicketService.getF1(startDate,endDate,lineCode);
               BigDecimal F2 = getSystemClearLongValueByLineCode(listSystemClearData,lineCode,"traffic");//dailyReportMap.get("F2");改为从系统清分获取
               //西安地铁和西咸的单独获取长安通刷卡消费和交通一卡通总计
			  /*
			  if(SwCkClearRuleConstans.SERVICE_ID_XADT.equals(serviceId) || SwCkClearRuleConstans.SERVICE_ID_XIXIAN.equals(serviceId)){  
                   Map<String,Long> subwayCatMap = swCkSysCleaningConsTicketService.getXasubwayCatTicketPayCardAndTrafficCardMap(startDate,endDate,lineCode);
                   E2 = subwayCatMap.get("E2");
				   F2 = subwayCatMap.get("F2");
               }*/

			   BigDecimal G1 = new BigDecimal(String.valueOf(dailyReportMap.get("G1")));
               BigDecimal G2 = new BigDecimal(String.valueOf(dailyReportMap.get("G2")));
               BigDecimal G3 = new BigDecimal(String.valueOf(dailyReportMap.get("G3")));
               BigDecimal G8 = new BigDecimal(String.valueOf(dailyReportMap.get("G8")));//收入日报 智码APP代售 目前只有西安地铁日报表有
			   BigDecimal G10 = new BigDecimal(String.valueOf(dailyReportMap.get("G10")));//应急及互联互通金额合计

               BigDecimal G4 = swCkSysCleaningConsTicketService.getG4(startDate,endDate,lineCode);
               BigDecimal G5 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG5(startDate,endDate,lineCode); 不需要查
               BigDecimal G6 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG6(startDate,endDate,lineCode);
               BigDecimal G7 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG7(startDate,endDate,lineCode);
               BigDecimal G9 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG9(startDate,endDate,lineCode);
              
			   BigDecimal H1 = new BigDecimal(String.valueOf(dailyReportMap.get("H1")));
               BigDecimal H2 = swCkSysCleaningConsTicketService.getH2(startDate,endDate,lineCode);//人脸

               BigDecimal I = C6.add(E2).add(F2).add(G4).add(G5).add(G6).add(G7).add(G9).add(H2);//不加D8，I值是否加应急及互联互通G10确定后再改  TODO  2021-11-08

               sumB0 = sumB0.add(B0);
               sumC6 = sumC6.add(C6);
               sumE1 = sumE1.add(E1);
               sumE2 = sumE2.add(E2);
               sumF1 = sumF1.add(F1);
               sumF2 = sumF2.add(F2);
               sumH1 = sumH1.add(H1);
               sumH2 = sumH2.add(H2);
               sumD3 = sumD3.add(D3);
			   sumG0 = sumG0.add(G1).add(G2).add(G3).add(G8).add(G10);//G1+G2+G3+G8-G4  应急及互联互通加入到二维码消费中一起计算清分
			   sumGn = sumGn.add(G4);
               //sumD8 += D8;
               sumI = sumI.add(I);
               mapB1.put(lineCode,B1);
               mapB2.put(lineCode,B2);
               mapB3.put(lineCode,B3);
               mapB4.put(lineCode,B4);
               mapB5.put(lineCode,B5);
               mapB6.put(lineCode,new BigDecimal(String.valueOf(B6)));
               mapC1.put(lineCode,C1);
               mapC2.put(lineCode,C2);
               mapC3.put(lineCode,C3);
               mapC4.put(lineCode,C4);
               mapC5.put(lineCode,C5);
			   //mapC61.put(lineCode,C61);
           
               mapD1.put(lineCode,D1);
               mapD2.put(lineCode,D2);
               mapD3.put(lineCode,D3);
               //mapD8.put(lineCode,D8);
               mapE1.put(lineCode,E1);
               mapE2.put(lineCode,E2);
               mapF1.put(lineCode,F1);
               mapF2.put(lineCode,F2);
               mapG4.put(lineCode,G4);
               mapG5.put(lineCode,G5);
               mapG6.put(lineCode,G6);
               mapG7.put(lineCode,G7);
			   mapG9.put(lineCode,G9);
			   mapG10.put(lineCode,G10);
               mapH2.put(lineCode,H2);
               mapDailyReport.put(lineCode, dailyReportMap);
               mapServiceId.put(lineCode, serviceId);
			   sumXianSubwayI = sumXianSubwayI.add(I);

           }
           BigDecimal decimal = new BigDecimal("0");
           BigDecimal decimal100 = new BigDecimal("100");
           int scale7 = 7;
           //插入数据库
           PigxUser user = SecurityUtils.getUser();
           List<SwCkClearAccountDetail> listSwCkClearAccountDetail = new ArrayList<>();
           List<SwCkClearDetail> listSwCkClearDetail = new ArrayList<>();

           for (String lineCode : listLine) {

               Map<String,Object> dailyReportMap = mapDailyReport.get(lineCode);
			   String serviceId = mapServiceId.get(lineCode);

               BigDecimal A1 = new BigDecimal(String.valueOf(dailyReportMap.get("A1")));
               BigDecimal A2 = new BigDecimal(String.valueOf(dailyReportMap.get("A2")));
               BigDecimal A3 = new BigDecimal(String.valueOf(dailyReportMap.get("A3")));
               BigDecimal A4 = new BigDecimal(String.valueOf(dailyReportMap.get("A4")));

               BigDecimal A0 = A1.add(A2).add(A3).add(A4);
               
               //增加单程票的现金和电子，但不需要累加到A0中  2021-03-22 追加
               BigDecimal A5 = new BigDecimal(String.valueOf(dailyReportMap.get("A5")));
               BigDecimal A6 = new BigDecimal(String.valueOf(dailyReportMap.get("A6")));

               BigDecimal B1 = mapB1.get(lineCode);
               BigDecimal B2 = mapB2.get(lineCode);
               BigDecimal B3 = mapB3.get(lineCode);
               BigDecimal B4 = mapB4.get(lineCode);
               BigDecimal B5 = mapB5.get(lineCode);
               BigDecimal B6 = mapB6.get(lineCode);
               BigDecimal B0 = B1.add(B2).add(B3).add(B4).subtract(B5).subtract(B6);
               BigDecimal C1 = mapC1.get(lineCode);
               BigDecimal C2 = mapC2.get(lineCode);
               BigDecimal C3 = mapC3.get(lineCode);
               BigDecimal C4 = mapC4.get(lineCode);
               BigDecimal C5 = mapC5.get(lineCode);
               //BigDecimal C61 = mapC61.get(lineCode);
               BigDecimal C6 = C1.add(C2).add(C3).add(C4).add(C5);//.add(C61);
			   //log.info("获取的C值为---C1--------"+C1+"----------------C2----"+C2+"----------------C3---"+C3+"----------------C4----"+C4+"----------------C5--"+C5+"----------------C6---"+C6);


               BigDecimal D1 = new BigDecimal(String.valueOf(dailyReportMap.get("D1")));
               BigDecimal D2 = new BigDecimal(String.valueOf(dailyReportMap.get("D2")));
               BigDecimal D3 = new BigDecimal(String.valueOf(dailyReportMap.get("D3")));
               
               //依次增加日票的现金和电子，纪念票的现金和电子金额，D4~D7但不需要累加到K中  2021-03-22 追加
               BigDecimal D4 = new BigDecimal(String.valueOf(dailyReportMap.get("D4")));
               BigDecimal D5 = new BigDecimal(String.valueOf(dailyReportMap.get("D5")));
               BigDecimal D6 = new BigDecimal(String.valueOf(dailyReportMap.get("D6")));
               BigDecimal D7 = new BigDecimal(String.valueOf(dailyReportMap.get("D7")));
               BigDecimal D8 = mapD8.get(lineCode);

               BigDecimal E1 =mapE1.get(lineCode);
               BigDecimal E2 =mapE2.get(lineCode);
               BigDecimal F1 =mapF1.get(lineCode);
               BigDecimal F2 =mapF2.get(lineCode);

               BigDecimal G1 = new BigDecimal(String.valueOf(dailyReportMap.get("G1")));
               BigDecimal G2 = new BigDecimal(String.valueOf(dailyReportMap.get("G2")));
               BigDecimal G3 = new BigDecimal(String.valueOf(dailyReportMap.get("G3")));
               BigDecimal G8 = new BigDecimal(String.valueOf(dailyReportMap.get("G8")));//收入日报 智码APP代售 目前只有西安地铁日报表有

			   BigDecimal G10 = new BigDecimal(String.valueOf(dailyReportMap.get("G10")));//收入日报 应急互联互通各个线路都有

               BigDecimal G4 = mapG4.get(lineCode);
               BigDecimal G5 = new BigDecimal("0");//mapG5.get(lineCode);
               BigDecimal G6 = new BigDecimal("0");//mapG6.get(lineCode);
               BigDecimal G7 = new BigDecimal("0");//mapG7.get(lineCode);
               BigDecimal G9 = new BigDecimal("0");//mapG9.get(lineCode);
               BigDecimal H1 = new BigDecimal(String.valueOf(dailyReportMap.get("H1")));;
               BigDecimal H2 = mapH2.get(lineCode);
               BigDecimal I = C6.add(E2).add(F2).add(G4).add(G5).add(G6).add(G7).add(G9).add(H2);//不加D8  I值是否加应急及互联互通G10确定后再改  TODO  2021-11-08

               Double J1 = 0D;
               String ruleKey = SwCkClearRuleConstans.CLEAR_RULE_MANMADE+","+"1"+","+serviceId+","+lineCode;
               if(mapLineClearRule!=null && !"".equals(mapLineClearRule.get(ruleKey))){
            	   J1 = Double.valueOf(getData2(mapLineClearRule.get(ruleKey)));
               }
               
               /*从规则表中直接获取
               if(sumI.doubleValue() - sumH2.doubleValue() != 0) {
                   J1 = (I.doubleValue()) / (sumI.doubleValue()) ;
               }*/

               BigDecimal C7 = ((sumB0.subtract(sumC6)).multiply(new BigDecimal(String.valueOf(J1))).divide(decimal100)).setScale(scale7,BigDecimal.ROUND_HALF_UP);
               BigDecimal C = A0.subtract(B0).add(C6).add(C7);
               
               //Long D9 = Math.round((sumD3.doubleValue() - sumD8.doubleValue()) * J1); //纪念票协议清分

               BigDecimal E0 = ((sumE1.subtract(sumE2)).multiply(new BigDecimal(String.valueOf(J1))).divide(decimal100)).setScale(scale7,BigDecimal.ROUND_HALF_UP);
               BigDecimal F0 = ((sumF1.subtract(sumF2)).multiply(new BigDecimal(String.valueOf(J1))).divide(decimal100)).setScale(scale7,BigDecimal.ROUND_HALF_UP);
               //计算G0  二维码包括应急及互联互通G10的计算待定 TODO    2021-11-08
               //BigDecimal G0 = ((G1.add(G2).add(G3).add(G8).subtract(G4).subtract(G5).subtract(G6).subtract(G7).subtract(G9)).divide(decimal100)).setScale(scale7,BigDecimal.ROUND_HALF_UP);
               BigDecimal G0 = ((sumG0.subtract(sumGn)).multiply(new BigDecimal(String.valueOf(J1))).divide(decimal100)).setScale(scale7,BigDecimal.ROUND_HALF_UP);//（消费-系统清分）*协议清分比例
               BigDecimal H0 = ((sumH1.subtract(sumH2)).multiply(new BigDecimal(String.valueOf(J1))).divide(decimal100)).setScale(scale7,BigDecimal.ROUND_HALF_UP);//（消费-系统清分）*含人脸的协议清分比例

               BigDecimal K = I.add(C).add(D1).add(D2).add(D3).add(E0).add(F0).add(G0).add(H0);


               SwCkClearAccountDetail swCkClearAccountDetail = new SwCkClearAccountDetail();

               swCkClearAccountDetail.setBeginTime(LocalDate.parse(startDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
               swCkClearAccountDetail.setEndTime(LocalDate.parse(endDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
               swCkClearAccountDetail.setLineCode(lineCode);

               //TODO  根据日期范围+线路 判断是否存在 ，存在更新，不存在插入
			   boolean isReClean = false;  //是否存在清分数据标识
               QueryWrapper<SwCkClearAccountDetail> query = Wrappers.query(swCkClearAccountDetail);
               SwCkClearAccountDetail detail = swCkClearAccountDetailService.getOne(query);
               String uuid = UUID.randomUUID().toString().toLowerCase();
               if(ObjectUtil.isNotEmpty(detail)){
                   swCkClearAccountDetail.setId(detail.getId());
                   swCkClearAccountDetail.setUpdateTime(LocalDateTime.now());
                   swCkClearAccountDetail.setRalationId(detail.getRalationId());
				   isReClean = true;
               }else {
                   swCkClearAccountDetail.setRalationId(uuid);// TODO  验证是否存在需要调整
               }

               swCkClearAccountDetail.setPaidinPreticket(A1);//单程票实收-预制单程票发售(分)
               swCkClearAccountDetail.setPaidinInternetTicket(A2);//单程票实收-预制单程票互联网购票(分)
               swCkClearAccountDetail.setPaidinOnewayTicket(A3);//单程票实收-单程票(分)
               swCkClearAccountDetail.setPaidinLongPayment(A4);//单程票实收-长款(分)
               swCkClearAccountDetail.setPaidinOnewaySum(A0);//单程票实收-小计(分)
               swCkClearAccountDetail.setPaidinOnewayCashSum(A5);//单程票实收-现金小计(分)
               swCkClearAccountDetail.setPaidinOnewayEleSum(A6);//单程票实收-电子小计(分)

               swCkClearAccountDetail.setReceivablePreticket(B1);//单程票对应的应收
               swCkClearAccountDetail.setReceivableInternetTicket(B2);
               swCkClearAccountDetail.setReceivableOnewayTicket(B3);
               swCkClearAccountDetail.setReceivableOnewayFare(B4);
               swCkClearAccountDetail.setReceivableOnewayRefund(B5);
               swCkClearAccountDetail.setReceivableOnewayOffset(B6);
               swCkClearAccountDetail.setReceivableOnewaySum(B0);

               swCkClearAccountDetail.setPayableOutClean(C1);//单程票应付-出站票清分(分)
               swCkClearAccountDetail.setPayablePreticketClean(C2);//单程票应付-预制票清分(分)
               swCkClearAccountDetail.setPayableOnewayClean(C3);////单程票应付-单程票消费清分(分)
               swCkClearAccountDetail.setPayableOnewayCleanFare(C4);//单程票应付-长安通现金补票清分(分)
               swCkClearAccountDetail.setPayableOnewayCleanOnlySale(C5);//单程票应付-单销售清分(分)
               swCkClearAccountDetail.setReceivableOnewayAccSum(C6);//单程票应付-ACC系统清分合计(分)  ---TODO  再增加恢复交易销售数量放到C6
			   //log.info("swCkClearAccountDetail.setReceivableOnewayAccSum====="+swCkClearAccountDetail.getReceivableOnewayAccSum());
			   //select money from sw_ck_sys_cleaning_cons_type  where CLEAN_TYPE='57'
                // where    TRADE_DATE BETWEEN '2021-07-02' and  '2021-08-01' and CLEAN_TYPE='57'  开始和结束日期都加1天再查
               swCkClearAccountDetail.setReceivableOnewayAgreeClean(C7);//单程票应付-协议清分(分)
               swCkClearAccountDetail.setReceivableOnewayReceivedClean(C);//单程票-实收清分结果(分)

               swCkClearAccountDetail.setCountingTicket(D1);
               swCkClearAccountDetail.setDailyTicket(D2);
               swCkClearAccountDetail.setCommemorativeTicket(D3);
               
               swCkClearAccountDetail.setDailyTicketCashSum(D4);
               swCkClearAccountDetail.setDailyTicketEleSum(D5);
               
               swCkClearAccountDetail.setCommemorativeTicketCashSum(D6);
               swCkClearAccountDetail.setCommemorativeTicketEleSum(D7);  
               swCkClearAccountDetail.setReceivableCommemorativeTicketAccSum(decimal);//纪念票系统清分  D8
               swCkClearAccountDetail.setReceivableCommemorativeTicketAgreeClean(decimal);//纪念票协议清分D9
            

               swCkClearAccountDetail.setCatTicketPay(E1);
               swCkClearAccountDetail.setCatSystemClean(E2);
               swCkClearAccountDetail.setCatAgreeClean(E0);

               swCkClearAccountDetail.setTrafficCardPay(F1);
               swCkClearAccountDetail.setTrafficCardSystemClean(F2);
               swCkClearAccountDetail.setTrafficCardAgreeClean(F0);

               swCkClearAccountDetail.setQrCodeTicketAlipay(G1);
               swCkClearAccountDetail.setQrCodeTicketWechat(G2);
               swCkClearAccountDetail.setQrCodeTicketUnionpay(G3);
			   swCkClearAccountDetail.setQrCodeTicketApp(G8);//收入日报-地铁APP代售
               swCkClearAccountDetail.setQrConnectivitySubTotal(G10);//增加应急及互联互通  2021-11-08
               swCkClearAccountDetail.setQrCodeTicketAlipaySystemClean(G4);//只保留查G4一个 ，用来合计就行，其他不管 G5，G6，G7，G9  TODO
               swCkClearAccountDetail.setQrCodeTicketWechatSystemClean(G5);
               swCkClearAccountDetail.setQrCodeTicketUnionpaySystemClean(G6);
			   swCkClearAccountDetail.setQrCodeTicketAppSystemClean(G9);//地铁APP代售
               swCkClearAccountDetail.setQrCodeTicketZfSystemClean(G7);
               swCkClearAccountDetail.setQrCodeTicketAgreeClean(G0);
               swCkClearAccountDetail.setFaceTicketCcb(H1);
               swCkClearAccountDetail.setFaceTicketSystemClean(H2);
               swCkClearAccountDetail.setFaceTicketAgreeClean(H0);
               swCkClearAccountDetail.setSystemCleanSum(I);
               swCkClearAccountDetail.setAgreeCleanRatio(new BigDecimal(J1).setScale(4, BigDecimal.ROUND_HALF_UP));
               swCkClearAccountDetail.setFaceTicketAgreeCleanRatio(new BigDecimal(J1).setScale(4, BigDecimal.ROUND_HALF_UP));
               swCkClearAccountDetail.setIncomeTotal(K);

               swCkClearAccountDetail.setOperators(serviceId);

               swCkClearAccountDetail.setDeptId(user.getDeptId());
               swCkClearAccountDetail.setCreatorId(user.getId());
               swCkClearAccountDetail.setCreatorName(user.getNikeName());

//			   if(isReClean){//重新清分操作，需要记录清分后数据差异  20210905  TODO
//				     //根据新老数据生成“清分后数据差异表”
//                     gensSwCkDiffAfterClear(detail,swCkClearAccountDetail);
//					 swCkClearAccountDetail.setUpdateTime(LocalDateTime.now());
//			   }

               listSwCkClearAccountDetail.add(swCkClearAccountDetail);

               //清分及划账
               SwCkClearDetail swCkClearDetail = new SwCkClearDetail();
               swCkClearDetail.setLineCode(lineCode);
               swCkClearDetail.setBeginTime(LocalDate.parse(startDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
               swCkClearDetail.setEndTime(LocalDate.parse(endDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
               //TODO  根据日期范围+线路 判断是否存在 ，存在更新，不存在插入
               QueryWrapper<SwCkClearDetail> queryDetail = Wrappers.query(swCkClearDetail);
               SwCkClearDetail ClearDetail = this.getOne(queryDetail);
               if(ObjectUtil.isNotEmpty(ClearDetail)){
                   swCkClearDetail.setId(ClearDetail.getId());
                   swCkClearDetail.setUpdateTime(LocalDateTime.now());
               }
               swCkClearDetail.setUuid(swCkClearAccountDetail.getRalationId());//TODO  主表存在更新的情况下，是否需要考虑？？？？？？
               swCkClearDetail.setAgreeTicketClearProportionOther(String.valueOf(J1));
               swCkClearDetail.setFaceTicketClearProportion(String.valueOf(J1));

               swCkClearDetail.setWaitClearAmount(A0.add(D1).add(D2).add(D3).add(E2).add(F2).add(G1).add(G2).add(G3).add(G8).add(G10).add(H1));//主表 待清分金额
               swCkClearDetail.setSysClearAmount(I);//系统清分金额
               swCkClearDetail.setManmadeClearAmount(C7.add(E0).add(F0).add(G0).add(H0));//人工清分金额  去掉D9
               swCkClearDetail.setTotalAmount(swCkClearDetail.getSysClearAmount().add(swCkClearDetail.getManmadeClearAmount()));
               swCkClearDetail.setEmeTicketRecoveryAmount(decimal);
               swCkClearDetail.setEmeTicketSaleAmount(decimal);
               swCkClearDetail.setEmeTicketClearAmount(decimal);
               swCkClearDetail.setManRefundAmount(decimal);
               swCkClearDetail.setManRefundClearAmount(decimal);

               swCkClearDetail.setDeptId(user.getDeptId());
               swCkClearDetail.setCreatorId(user.getId());
               swCkClearDetail.setCreatorName(user.getNikeName());

			    if(isReClean){//重新清分操作 20210905  TODO			         
				    swCkClearDetail.setUpdateTime(LocalDateTime.now());
			   }


               listSwCkClearDetail.add(swCkClearDetail);

           }

           if(listSwCkClearAccountDetail != null && !listSwCkClearAccountDetail.isEmpty()){
               swCkClearAccountDetailService.saveOrUpdateBatch(listSwCkClearAccountDetail);
               flag  = true;
           }
           if(listSwCkClearDetail != null && !listSwCkClearDetail.isEmpty()) {
               this.saveOrUpdateBatch(listSwCkClearDetail);
               flag  = true;
           }

           //生成清分后数据差异表处理
           createSwCkDiffAfterClear(startDate,endDate);
       }
	   log.info("正常清分---系统自动计算结束于:{}", LocalDateTime.now());
       return flag;
   }

    private void createSwCkDiffAfterClear(String startDate, String endDate) {
        PigxUser user = SecurityUtils.getUser();
        List<SwCkDiffAfterClear> list = new ArrayList<>();
        //查询 根据开始时间+结束时间查询清分后数据差异表是否存在
        SwCkDiffAfterClear swCkDiffAfterClear = new SwCkDiffAfterClear();
        swCkDiffAfterClear.setBeginTime(LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        swCkDiffAfterClear.setEndTime(LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        QueryWrapper<SwCkDiffAfterClear> queryWrappers = Wrappers.query(swCkDiffAfterClear);
        queryWrappers.orderByAsc("OPERATORS","CAST(LINE_CODE AS SIGNED)");
        List<SwCkDiffAfterClear> swCkDiffAfterClearList = swCkDiffAfterClearService.list(queryWrappers);

        ////调用运营商收入清分报表查询方法（开始日期+结束日期）获取查询结果插入或者更新到清分后数据差异表内。
        //查询运营商收入清分报表
        ViewCkOperatorsTicketRevenueClear viewCkOperatorsTicketRevenueClear = new ViewCkOperatorsTicketRevenueClear();
        viewCkOperatorsTicketRevenueClear.setBeginTime(LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        viewCkOperatorsTicketRevenueClear.setEndTime(LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        QueryWrapper<ViewCkOperatorsTicketRevenueClear> wrapper = Wrappers.query(viewCkOperatorsTicketRevenueClear);
        wrapper.orderByAsc("OPERATORS","CAST(LINE_CODE AS SIGNED)");
        List<ViewCkOperatorsTicketRevenueClear> viewList = viewCkOperatorsTicketRevenueClearService.list(wrapper);

        BigDecimal decimal100 = new BigDecimal("100");

        if(CollectionUtil.isNotEmpty(viewList)){
            //不存在，插入数据，记录到首次清分金额
            if(CollectionUtil.isEmpty(swCkDiffAfterClearList)){
                for (ViewCkOperatorsTicketRevenueClear revenueClear : viewList) {
                    SwCkDiffAfterClear firstDiffAfterClear = new SwCkDiffAfterClear();
                    firstDiffAfterClear.setBeginTime(revenueClear.getBeginTime());
                    firstDiffAfterClear.setEndTime(revenueClear.getEndTime());
                    firstDiffAfterClear.setOperators(revenueClear.getOperators());
                    firstDiffAfterClear.setLineCode(revenueClear.getLineCode());
                    firstDiffAfterClear.setFirstReceivableOnewayReceivedClean(revenueClear.getReceivableOnewayReceivedClean().multiply(decimal100));
                    firstDiffAfterClear.setFirstReturnOnewayReceivedClean(revenueClear.getReturnOnewayReceivedClean().multiply(decimal100));
                    firstDiffAfterClear.setFirstSumOnewayReceivedClean(revenueClear.getSumOnewayReceivedClean().multiply(decimal100));
                    firstDiffAfterClear.setFirstCountingTicket(revenueClear.getCountingTicket().multiply(decimal100));
                    firstDiffAfterClear.setFirstDailyTicket(revenueClear.getDailyTicket().multiply(decimal100));
                    firstDiffAfterClear.setFirstCommemorativeTicket(revenueClear.getCommemorativeTicket().multiply(decimal100));
                    firstDiffAfterClear.setFirstCat(revenueClear.getCat().multiply(decimal100));
                    firstDiffAfterClear.setFirstTrafficCard(revenueClear.getTrafficCard().multiply(decimal100));
                    firstDiffAfterClear.setFirstQrCodeTicket(revenueClear.getQrCodeTicket().multiply(decimal100));
                    firstDiffAfterClear.setFirstFaceTicketCcb(revenueClear.getFaceTicketCcb().multiply(decimal100));
                    firstDiffAfterClear.setFirstIncomeSubtotal(revenueClear.getIncomeSubtotal().multiply(decimal100));
                    firstDiffAfterClear.setDeptId(user.getDeptId());
                    firstDiffAfterClear.setCreatorId(user.getId());
                    firstDiffAfterClear.setCreatorName(user.getNikeName());
                    list.add(firstDiffAfterClear);
                }
            }else {//存在，更新最新清分金额
                for (int i = 0; i < viewList.size(); i++) {
                    ViewCkOperatorsTicketRevenueClear revenueClear = viewList.get(i);
                    SwCkDiffAfterClear diffAfterClear = swCkDiffAfterClearList.get(i);
                    diffAfterClear.setCurrentReceivableOnewayReceivedClean(revenueClear.getReceivableOnewayReceivedClean().multiply(decimal100));
                    diffAfterClear.setCurrentReturnOnewayReceivedClean(revenueClear.getReturnOnewayReceivedClean().multiply(decimal100));
                    diffAfterClear.setCurrentSumOnewayReceivedClean(revenueClear.getSumOnewayReceivedClean().multiply(decimal100));
                    diffAfterClear.setCurrentCountingTicket(revenueClear.getCountingTicket().multiply(decimal100));
                    diffAfterClear.setCurrentDailyTicket(revenueClear.getDailyTicket().multiply(decimal100));
                    diffAfterClear.setCurrentCommemorativeTicket(revenueClear.getCommemorativeTicket().multiply(decimal100));
                    diffAfterClear.setCurrentCat(revenueClear.getCat().multiply(decimal100));
                    diffAfterClear.setCurrentTrafficCard(revenueClear.getTrafficCard().multiply(decimal100));
                    diffAfterClear.setCurrentQrCodeTicket(revenueClear.getQrCodeTicket().multiply(decimal100));
                    diffAfterClear.setCurrentFaceTicketCcb(revenueClear.getFaceTicketCcb().multiply(decimal100));
                    diffAfterClear.setCurrentIncomeSubtotal(revenueClear.getIncomeSubtotal().multiply(decimal100));
                    list.add(diffAfterClear);
                }
            }
        }

        //更新或者修改
        swCkDiffAfterClearService.saveOrUpdateBatch(list);

    }

    /**
     * 重新清分，生成“清分后数据差异表”  此方法需要废弃掉 20210905
     * @param ids 清分及划账记录的ID
     * @return
     */
    public Boolean reGenerateSwCkClearDetail(List<Long> ids) {
        boolean flag = false;
        PigxUser user = SecurityUtils.getUser();
        for(Long id : ids) {
            SwCkClearDetail swCkClearDetailDb = this.getById(id);
            String lineCodePar = swCkClearDetailDb.getLineCode();
            String startDate = swCkClearDetailDb.getBeginTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String endDate = swCkClearDetailDb.getEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
			Map<String,String> mapLineClearRule = swCkClearRuleService.selectRulesDetailsMapByDate(startDate, endDate) ;


            //获取时间段内的西安地铁和其他运营商的线路列表
            List<String> listLine = this.baseMapper.selectLineList(startDate,endDate);
            if (listLine != null && !listLine.isEmpty()) {

                BigDecimal sumB0 = new BigDecimal("0");
                BigDecimal sumC6 = new BigDecimal("0");
                BigDecimal sumI = new BigDecimal("0");
                BigDecimal sumXianSubwayI = new BigDecimal("0");

                BigDecimal sumE1 = new BigDecimal("0");
                BigDecimal sumE2 = new BigDecimal("0");

                BigDecimal sumF1 = new BigDecimal("0");
                BigDecimal sumF2 = new BigDecimal("0");

                BigDecimal sumH1 = new BigDecimal("0");
                BigDecimal sumH2 = new BigDecimal("0");

                BigDecimal sumD3 = new BigDecimal("0");//所有线路的纪念票合计
                BigDecimal sumD8 = new BigDecimal("0");//所有线路的纪念票系统清分合计


                String xianSubwayServiceId = "1";//swCkSysCleaningConsTicketService.getSubwayServiceIdByName("西安地铁");
                //从线路表获取西咸的serviceid ,目前返回71 ，（该serviceid包括1号线二期和五号线二期)。
                String xixianSubwayServiceId = "71";//swCkSysCleaningConsTicketService.getSubwayServiceIdByName("西咸"); //
                String airSubwayServiceId = "54";//swCkSysCleaningConsTicketService.getSubwayServiceIdByName("陕西铁路集团");
				
				  //存放临时变量到内存中，减少SQL查询

                Map<String,BigDecimal> mapB1 = new HashMap();
                Map<String,BigDecimal> mapB2 = new HashMap();
                Map<String,BigDecimal> mapB3 = new HashMap();
                Map<String,BigDecimal> mapB4 = new HashMap();
                Map<String,BigDecimal> mapB5 = new HashMap();
                Map<String,BigDecimal> mapB6 = new HashMap();
                Map<String,BigDecimal> mapC1 =new HashMap();
                Map<String,BigDecimal> mapC2 =new HashMap();
                Map<String,BigDecimal> mapC3 =new HashMap();
                Map<String,BigDecimal> mapC4 =new HashMap();
                Map<String,BigDecimal> mapC5 =new HashMap();
               // Map<String,BigDecimal> mapC61 =new HashMap();

                Map<String,BigDecimal> mapD1 =new HashMap();
                Map<String,BigDecimal> mapD2 =new HashMap();
                Map<String,BigDecimal> mapD3 =new HashMap();
                Map<String,BigDecimal> mapD8 =new HashMap();
                Map<String,BigDecimal> mapE1 =new HashMap();
                Map<String,BigDecimal> mapE2 =new HashMap();
                Map<String,BigDecimal> mapF1 =new HashMap();
                Map<String,BigDecimal> mapF2 =new HashMap();
                Map<String,BigDecimal> mapG4 = new HashMap();
                Map<String,BigDecimal> mapG5 = new HashMap();
                Map<String,BigDecimal> mapG6 = new HashMap();
                Map<String,BigDecimal> mapG7 = new HashMap();
                Map<String,BigDecimal> mapG9 = new HashMap();
                Map<String,BigDecimal> mapH2 = new HashMap();
			   Map<String,Map<String,Object>> mapDailyReport = new HashMap();
			   Map<String,String> mapServiceId = new HashMap();

			   List<Map<String,Object>> listSystemClearData = swCkSysCleaningConsTicketService.getE2F2(startDate,endDate);

                //计算合计值
                for (String lineCode : listLine) {
                    //各指标定义,参见word文档,下同
					 //根据线路ID，返回不同日报表的数据。目前包括西安地铁、西咸、西安中铁和机场城际四个日报表
                    String serviceId = swCkSysCleaningConsTicketService.getServiceOrgByLine(lineCode).get("serviceId");
                    Map<String,Object> dailyReportMap = swCkSysCleaningConsTicketService.getDailyReportMap(startDate,endDate,lineCode,serviceId);

                    BigDecimal B1 = new BigDecimal(String.valueOf(dailyReportMap.get("B1")));
                    BigDecimal B2 = new BigDecimal(String.valueOf(dailyReportMap.get("B2")));
                    BigDecimal B3 = swCkSysCleaningConsTicketService.getB3(startDate,endDate,lineCode);
                    BigDecimal B4 = swCkSysCleaningConsTicketService.getB4(startDate,endDate,lineCode);
                    BigDecimal B5 = swCkSysCleaningConsTicketService.getB5(startDate,endDate,lineCode);
                    Long B6 = swCkSysCleaningConsTicketService.getB6(startDate,endDate,lineCode);
                    BigDecimal B0 = B1.add(B2).add(B3).add(B4).subtract(B5).subtract(new BigDecimal(String.valueOf(B6)));

                    BigDecimal C1 = swCkSysCleaningConsTicketService.getC1(startDate,endDate,lineCode);
                    BigDecimal C2 = swCkSysCleaningConsTicketService.getC2(startDate,endDate,lineCode);
                    BigDecimal C3 = swCkSysCleaningConsTicketService.getC3(startDate,endDate,lineCode);
                    BigDecimal C4 = swCkSysCleaningConsTicketService.getC4(startDate,endDate,lineCode);
                    BigDecimal C5 = swCkSysCleaningConsTicketService.getC5(startDate,endDate,lineCode);
                    //BigDecimal C61 = swCkSysCleaningConsTicketService.getC61(startDate,endDate,lineCode);
                    BigDecimal C6 = C1.add(C2).add(C3).add(C4).add(C5);//;.add(C61);


                    BigDecimal D1 = new BigDecimal(String.valueOf(dailyReportMap.get("D1")));
                    BigDecimal D2 = new BigDecimal(String.valueOf(dailyReportMap.get("D2")));
                    BigDecimal D3 = new BigDecimal(String.valueOf(dailyReportMap.get("D3")));

                    //Long D8 = swCkSysCleaningConsTicketService.getD8(startDate,endDate,lineCode);

                    BigDecimal E1 = swCkSysCleaningConsTicketService.getE1(startDate,endDate,lineCode);
                    BigDecimal E2 = getSystemClearLongValueByLineCode(listSystemClearData,lineCode,"cat");//dailyReportMap.get("E2"); 改为从系统清分获取
                    BigDecimal F1 = swCkSysCleaningConsTicketService.getF1(startDate,endDate,lineCode);
                    BigDecimal F2 = getSystemClearLongValueByLineCode(listSystemClearData,lineCode,"traffic");//dailyReportMap.get("F2");改为从系统清分获取
					/*
					if(xianSubwayServiceId.equals(serviceId)|| xixianSubwayServiceId.equals(serviceId)){  
					   Map<String,Long> subwayCatMap = swCkSysCleaningConsTicketService.getXasubwayCatTicketPayCardAndTrafficCardMap(startDate,endDate,lineCode);
					   E2 = subwayCatMap.get("E2");
					   F2 = subwayCatMap.get("F2");
                    }*/

                    BigDecimal G4 = swCkSysCleaningConsTicketService.getG4(startDate,endDate,lineCode);
                    BigDecimal G5 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG5(startDate,endDate,lineCode); 不需要查
                    BigDecimal G6 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG6(startDate,endDate,lineCode);
                    BigDecimal G7 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG7(startDate,endDate,lineCode);
                    BigDecimal G9 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG9(startDate,endDate,lineCode);
                    BigDecimal H1 = new BigDecimal(String.valueOf(dailyReportMap.get("H1")));
                    BigDecimal H2 = swCkSysCleaningConsTicketService.getH2(startDate,endDate,lineCode);//人脸

                    BigDecimal I = C6.add(E2).add(F2).add(G4).add(G5).add(G6).add(G7).add(G9).add(H2);//不加D8

                    sumB0 = sumB0.add(B0);
                    sumC6 = sumC6.add(C6);
                    sumE1 = sumE1.add(E1);
                    sumE2 = sumE2.add(E2);
                    sumF1 = sumF1.add(F1);
                    sumF2 = sumF2.add(F2);
                    sumH1 = sumH1.add(H1);
                    sumH2 = sumH2.add(H2);
                    sumD3 = sumD3.add(D3);
                    //sumD8 += D8;
                    sumI = sumI.add(I);
                    sumXianSubwayI = sumXianSubwayI.add(I);

					   mapB1.put(lineCode,B1);
					   mapB2.put(lineCode,B2);
					   mapB3.put(lineCode,B3);
					   mapB4.put(lineCode,B4);
					   mapB5.put(lineCode,B5);
					   mapB6.put(lineCode,new BigDecimal(String.valueOf(B6)));
					   mapC1.put(lineCode,C1);
					   mapC2.put(lineCode,C2);
					   mapC3.put(lineCode,C3);
					   mapC4.put(lineCode,C4);
					   mapC5.put(lineCode,C5);
				   
					   mapD1.put(lineCode,D1);
					   mapD2.put(lineCode,D2);
					   mapD3.put(lineCode,D3);
					   //mapD8.put(lineCode,D8);
					   mapE1.put(lineCode,E1);
					   mapE2.put(lineCode,E2);
					   mapF1.put(lineCode,F1);
					   mapF2.put(lineCode,F2);
					   mapG4.put(lineCode,G4);
					   mapG5.put(lineCode,G5);
					   mapG6.put(lineCode,G6);
					   mapG7.put(lineCode,G7);
					   mapG9.put(lineCode,G9);
					   mapH2.put(lineCode,H2);
					   mapDailyReport.put(lineCode, dailyReportMap);
					   mapServiceId.put(lineCode, serviceId);
                }
                BigDecimal decimal = new BigDecimal("0");
                BigDecimal decimal100 = new BigDecimal("100");
                int scale7 = 7;
                /////////////////更新数据库 start/////////////
                Map<String,Object> dailyReportMap = mapDailyReport.get(lineCodePar);//swCkSysCleaningConsTicketService.getDailyReportMap(startDate,endDate,lineCodePar);
				String serviceId = mapServiceId.get(lineCodePar);//swCkSysCleaningConsTicketService.getServiceOrgByLine(lineCodePar).get("serviceId");

                BigDecimal A1 = new BigDecimal(String.valueOf(dailyReportMap.get("A1")));
                BigDecimal A2 = new BigDecimal(String.valueOf(dailyReportMap.get("A2")));
                BigDecimal A3 = new BigDecimal(String.valueOf(dailyReportMap.get("A3")));
                BigDecimal A4 = new BigDecimal(String.valueOf(dailyReportMap.get("A4")));

                BigDecimal A0 = A1.add(A2).add(A3).add(A4);

                //增加单程票的现金和电子，但不需要累加到A0中  2021-03-22 追加
                BigDecimal A5 = new BigDecimal(String.valueOf(dailyReportMap.get("A5")));
                BigDecimal A6 = new BigDecimal(String.valueOf(dailyReportMap.get("A6")));

                BigDecimal B1 = mapB1.get(lineCodePar);
                BigDecimal B2 = mapB2.get(lineCodePar);
                BigDecimal B3 = mapB3.get(lineCodePar);
                BigDecimal B4 = mapB4.get(lineCodePar);
                BigDecimal B5 = mapB5.get(lineCodePar);
                BigDecimal B6 = mapB6.get(lineCodePar);
                BigDecimal B0 = B1.add(B2).add(B3).add(B4).subtract(B5).subtract(B6);

                BigDecimal C1 = mapC1.get(lineCodePar);
                BigDecimal C2 = mapC2.get(lineCodePar);
                BigDecimal C3 = mapC3.get(lineCodePar);
                BigDecimal C4 = mapC4.get(lineCodePar);
                BigDecimal C5 = mapC5.get(lineCodePar);
                //BigDecimal C61 = mapC61.get(lineCodePar);
                BigDecimal C6 = C1.add(C2).add(C3).add(C4).add(C5);

                BigDecimal D1 = new BigDecimal(String.valueOf(dailyReportMap.get("D1")));
                BigDecimal D2 = new BigDecimal(String.valueOf(dailyReportMap.get("D2")));
                BigDecimal D3 = new BigDecimal(String.valueOf(dailyReportMap.get("D3")));

                //依次增加日票的现金和电子，纪念票的现金和电子金额，D4~D7但不需要累加到K中  2021-03-22 追加
                BigDecimal D4 = new BigDecimal(String.valueOf(dailyReportMap.get("D4")));
                BigDecimal D5 = new BigDecimal(String.valueOf(dailyReportMap.get("D5")));
                BigDecimal D6 = new BigDecimal(String.valueOf(dailyReportMap.get("D6")));
                BigDecimal D7 = new BigDecimal(String.valueOf(dailyReportMap.get("D7")));
                //BigDecimal D8 = mapD8.get(lineCodePar);

                BigDecimal E1 =mapE1.get(lineCodePar);
                BigDecimal E2 =mapE2.get(lineCodePar);
                BigDecimal F1 =mapF1.get(lineCodePar);
                BigDecimal F2 =mapF2.get(lineCodePar);

                BigDecimal G1 = new BigDecimal(String.valueOf(dailyReportMap.get("G1")));
                BigDecimal G2 = new BigDecimal(String.valueOf(dailyReportMap.get("G2")));
                BigDecimal G3 = new BigDecimal(String.valueOf(dailyReportMap.get("G3")));
                BigDecimal G8 = new BigDecimal(String.valueOf(dailyReportMap.get("G8")));//收入日报 智码APP代售 目前只有西安地铁日报表有

                BigDecimal G4 = mapG4.get(lineCodePar);
                BigDecimal G5 = new BigDecimal("0");//mapG5.get(lineCode);
                BigDecimal G6 = new BigDecimal("0");//mapG6.get(lineCode);
                BigDecimal G7 = new BigDecimal("0");//mapG7.get(lineCode);
                BigDecimal G9 = new BigDecimal("0");//mapG9.get(lineCode);
                BigDecimal H1 = new BigDecimal(String.valueOf(dailyReportMap.get("H1")));;
                BigDecimal H2 = mapH2.get(lineCodePar);
                BigDecimal I = C6.add(E2).add(F2).add(G4).add(G5).add(G6).add(G7).add(G9).add(H2);//不加D8

                Double J1 = 0D;
                String ruleKey = SwCkClearRuleConstans.CLEAR_RULE_MANMADE+","+"1"+","+serviceId+","+lineCodePar;
                if(mapLineClearRule!=null && !"".equals(mapLineClearRule.get(ruleKey))){
             	   J1 = Double.valueOf(getData2(mapLineClearRule.get(ruleKey)));
                }


                BigDecimal C7 = ((sumB0.subtract(sumC6)).multiply(new BigDecimal(String.valueOf(J1))).divide(decimal100)).setScale(scale7,BigDecimal.ROUND_HALF_UP);
                BigDecimal C = A0.subtract(B0).add(C6).add(C7);

                //Long D9 = Math.round((sumD3.doubleValue() - sumD8.doubleValue()) * J1); //纪念票协议清分

                BigDecimal E0 = ((sumE1.subtract(sumE2)).multiply(new BigDecimal(String.valueOf(J1))).divide(decimal100)).setScale(scale7,BigDecimal.ROUND_HALF_UP);
                BigDecimal F0 = ((sumF1.subtract(sumF2)).multiply(new BigDecimal(String.valueOf(J1))).divide(decimal100)).setScale(scale7,BigDecimal.ROUND_HALF_UP);

                BigDecimal G0 = ((G1.add(G2).add(G3).add(G8).subtract(G4).subtract(G5).subtract(G6).subtract(G7).subtract(G9)).divide(decimal100)).setScale(scale7,BigDecimal.ROUND_HALF_UP);

                BigDecimal H0 = ((sumH1.subtract(sumH2)).multiply(new BigDecimal(String.valueOf(J1))).divide(decimal100)).setScale(scale7,BigDecimal.ROUND_HALF_UP);//（消费-系统清分）*含人脸的协议清分比例

                BigDecimal K = I.add(C).add(D1).add(D2).add(D3).add(E0).add(F0).add(G0).add(H0);


                SwCkClearAccountDetail swCkClearAccountDetail = new SwCkClearAccountDetail();

                swCkClearAccountDetail.setBeginTime(LocalDate.parse(startDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                swCkClearAccountDetail.setEndTime(LocalDate.parse(endDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                swCkClearAccountDetail.setLineCode(lineCodePar);

                swCkClearAccountDetail.setPaidinPreticket(A1);
                swCkClearAccountDetail.setPaidinInternetTicket(A2);
                swCkClearAccountDetail.setPaidinOnewayTicket(A3);
                swCkClearAccountDetail.setPaidinLongPayment(A4);
                swCkClearAccountDetail.setPaidinOnewaySum(A0);
                swCkClearAccountDetail.setPaidinOnewayCashSum(A5);
                swCkClearAccountDetail.setPaidinOnewayEleSum(A6);

                swCkClearAccountDetail.setReceivablePreticket(B1);
                swCkClearAccountDetail.setReceivableInternetTicket(B2);
                swCkClearAccountDetail.setReceivableOnewayTicket(B3);
                swCkClearAccountDetail.setReceivableOnewayFare(B4);
                swCkClearAccountDetail.setReceivableOnewayRefund(B5);
                swCkClearAccountDetail.setReceivableOnewayOffset(B6);
                swCkClearAccountDetail.setReceivableOnewaySum(B0);

                swCkClearAccountDetail.setPayableOutClean(C1);
                swCkClearAccountDetail.setPayablePreticketClean(C2);
                swCkClearAccountDetail.setPayableOnewayClean(C3);
                swCkClearAccountDetail.setPayableOnewayCleanFare(C4);
                swCkClearAccountDetail.setPayableOnewayCleanOnlySale(C5);
                swCkClearAccountDetail.setReceivableOnewayAccSum(C6);
                swCkClearAccountDetail.setReceivableOnewayAgreeClean(C7);
                swCkClearAccountDetail.setReceivableOnewayReceivedClean(C);

                swCkClearAccountDetail.setCountingTicket(D1);
                swCkClearAccountDetail.setDailyTicket(D2);
                swCkClearAccountDetail.setCommemorativeTicket(D3);
                swCkClearAccountDetail.setDailyTicketCashSum(D4);
                swCkClearAccountDetail.setDailyTicketEleSum(D5);
                swCkClearAccountDetail.setCommemorativeTicketCashSum(D6);
                swCkClearAccountDetail.setCommemorativeTicketEleSum(D7); 
                swCkClearAccountDetail.setReceivableCommemorativeTicketAccSum(decimal);//纪念票系统清分D8
                swCkClearAccountDetail.setReceivableCommemorativeTicketAgreeClean(decimal);//纪念票协议清分D9

                swCkClearAccountDetail.setCatTicketPay(E1);
                swCkClearAccountDetail.setCatSystemClean(E2);
                swCkClearAccountDetail.setCatAgreeClean(E0);

                swCkClearAccountDetail.setTrafficCardPay(F1);
                swCkClearAccountDetail.setTrafficCardSystemClean(F2);
                swCkClearAccountDetail.setTrafficCardAgreeClean(F0);

                swCkClearAccountDetail.setQrCodeTicketAlipay(G1);
                swCkClearAccountDetail.setQrCodeTicketWechat(G2);
                swCkClearAccountDetail.setQrCodeTicketUnionpay(G3);
				swCkClearAccountDetail.setQrCodeTicketApp(G8);//地铁APP代售
                swCkClearAccountDetail.setQrCodeTicketAlipaySystemClean(G4);
                swCkClearAccountDetail.setQrCodeTicketWechatSystemClean(G5);
                swCkClearAccountDetail.setQrCodeTicketUnionpaySystemClean(G6);
				swCkClearAccountDetail.setQrCodeTicketAppSystemClean(G9);
                swCkClearAccountDetail.setQrCodeTicketZfSystemClean(G7);
                swCkClearAccountDetail.setQrCodeTicketAgreeClean(G0);
                swCkClearAccountDetail.setFaceTicketCcb(H1);
                swCkClearAccountDetail.setFaceTicketSystemClean(H2);
                swCkClearAccountDetail.setFaceTicketAgreeClean(H0);
                swCkClearAccountDetail.setSystemCleanSum(I);
                swCkClearAccountDetail.setAgreeCleanRatio(new BigDecimal(J1).setScale(4, BigDecimal.ROUND_HALF_UP));
                swCkClearAccountDetail.setFaceTicketAgreeCleanRatio(new BigDecimal(J1).setScale(4, BigDecimal.ROUND_HALF_UP));
                swCkClearAccountDetail.setIncomeTotal(K);

                swCkClearAccountDetail.setDeptId(user.getDeptId());
                swCkClearAccountDetail.setCreatorId(user.getId());
                swCkClearAccountDetail.setCreatorName(user.getNikeName());
                swCkClearAccountDetail.setOperators(serviceId);

                SwCkClearAccountDetail condition = new SwCkClearAccountDetail();
                condition.setRalationId(swCkClearDetailDb.getUuid());
                SwCkClearAccountDetail swCkClearAccountDetailDb = swCkClearAccountDetailService.getOne(Wrappers.query(condition));

                //根据新老数据生成“清分后数据差异表”
                gensSwCkDiffAfterClear(swCkClearAccountDetailDb,swCkClearAccountDetail);

                MyBeanUtils.copyProperties(swCkClearAccountDetail,swCkClearAccountDetailDb);
                swCkClearAccountDetailDb.setUpdateTime(LocalDateTime.now());
                swCkClearAccountDetailService.updateById(swCkClearAccountDetailDb);


                ///////////////清分及划账///////
                SwCkClearDetail swCkClearDetail = new SwCkClearDetail();
                swCkClearDetail.setLineCode(lineCodePar);
                swCkClearDetail.setBeginTime(LocalDate.parse(startDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                swCkClearDetail.setEndTime(LocalDate.parse(endDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                
                swCkClearDetail.setAgreeTicketClearProportionOther(String.valueOf(J1));
                swCkClearDetail.setFaceTicketClearProportion(String.valueOf(J1));

                swCkClearDetail.setWaitClearAmount(A0.add(D1).add(D2).add(D3).add(E2).add(F2).add(G1).add(G2).add(G3).add(G8).add(H1));//主表 待清分金额
                swCkClearDetail.setSysClearAmount(I);//系统清分金额
                swCkClearDetail.setManmadeClearAmount(C7.add(E0).add(F0).add(G0).add(H0));//人工清分金额  去掉D9
                swCkClearDetail.setTotalAmount(swCkClearDetail.getSysClearAmount().add(swCkClearDetail.getManmadeClearAmount()));
                swCkClearDetail.setEmeTicketRecoveryAmount(decimal);
                swCkClearDetail.setEmeTicketSaleAmount(decimal);
                swCkClearDetail.setEmeTicketClearAmount(decimal);
                swCkClearDetail.setManRefundAmount(decimal);
                swCkClearDetail.setManRefundClearAmount(decimal);

                swCkClearDetail.setDeptId(user.getDeptId());
                swCkClearDetail.setCreatorId(user.getId());
                swCkClearDetail.setCreatorName(user.getNikeName());

                MyBeanUtils.copyProperties(swCkClearDetail,swCkClearDetailDb);
                swCkClearDetailDb.setUpdateTime(LocalDateTime.now());
                this.updateById(swCkClearDetailDb);
                /////////////////更新数据库 end/////////////
                flag  = true;
            }
        }

        return flag;
    }

    /**
     * 生成清分后数据差异表数据
     */
    private void gensSwCkDiffAfterClear(SwCkClearAccountDetail lastObj, SwCkClearAccountDetail currObj){
        PigxUser user = SecurityUtils.getUser();
        List<SwCkDiffAfterClear> list = new ArrayList<>();
        for (int i = 0; i< 5; i++) {
            SwCkDiffAfterClear swCkDiffAfterClear = new SwCkDiffAfterClear();
            swCkDiffAfterClear.setOperators(currObj.getOperators());
            swCkDiffAfterClear.setLineCode(currObj.getLineCode());
            swCkDiffAfterClear.setBeginTime(currObj.getBeginTime());
            swCkDiffAfterClear.setEndTime(currObj.getEndTime());
            swCkDiffAfterClear.setLastClearDate(lastObj.getUpdateTime() != null ? lastObj.getUpdateTime().toLocalDate() : lastObj.getCreateTime().toLocalDate());
            swCkDiffAfterClear.setCurrClearDate(LocalDate.now());
            if(i==0){
                //单程票 C6 + C7
                swCkDiffAfterClear.setLastClearMoney(lastObj.getReceivableOnewayAccSum().add(lastObj.getReceivableOnewayAgreeClean()));
                swCkDiffAfterClear.setCurrClearMoney(currObj.getReceivableOnewayAccSum().add(currObj.getReceivableOnewayAgreeClean()));
                swCkDiffAfterClear.setTicketType("1");
            }
            if(i==1){
                //长安通 E2 + E0
                swCkDiffAfterClear.setLastClearMoney(lastObj.getCatSystemClean().add(lastObj.getCatAgreeClean()));
                swCkDiffAfterClear.setCurrClearMoney(currObj.getCatSystemClean().add(currObj.getCatAgreeClean()));
                swCkDiffAfterClear.setTicketType("4");
            }
            if(i==2){
                //交通卡 F2 + F0
                swCkDiffAfterClear.setLastClearMoney(lastObj.getTrafficCardSystemClean().add(lastObj.getTrafficCardAgreeClean()));
                swCkDiffAfterClear.setCurrClearMoney(currObj.getTrafficCardSystemClean().add(currObj.getTrafficCardAgreeClean()));
                swCkDiffAfterClear.setTicketType("3");
            }
            if(i==3){
                //二维码 G4 + G5 + G6 + G7 + G9 + G0
                swCkDiffAfterClear.setLastClearMoney(lastObj.getQrCodeTicketAlipaySystemClean().add(lastObj.getQrCodeTicketWechatSystemClean()).add(lastObj.getQrCodeTicketUnionpaySystemClean()).add(lastObj.getQrCodeTicketAppSystemClean()).add(lastObj.getQrCodeTicketZfSystemClean()).add(lastObj.getQrCodeTicketAgreeClean()));
                swCkDiffAfterClear.setCurrClearMoney(currObj.getQrCodeTicketAlipaySystemClean().add(currObj.getQrCodeTicketWechatSystemClean()).add(currObj.getQrCodeTicketUnionpaySystemClean()).add(currObj.getQrCodeTicketAppSystemClean()).add(currObj.getQrCodeTicketZfSystemClean()).add(currObj.getQrCodeTicketAgreeClean()));
                swCkDiffAfterClear.setTicketType("2");
            }
            if(i==4){
                //人脸电子票 H2 + H0
                swCkDiffAfterClear.setLastClearMoney(lastObj.getFaceTicketSystemClean().add(lastObj.getFaceTicketAgreeClean()));
                swCkDiffAfterClear.setCurrClearMoney(currObj.getFaceTicketSystemClean().add(currObj.getFaceTicketAgreeClean()));
                swCkDiffAfterClear.setTicketType("5");
            }

            swCkDiffAfterClear.setDiffMoney(swCkDiffAfterClear.getCurrClearMoney().subtract(swCkDiffAfterClear.getLastClearMoney()));
            swCkDiffAfterClear.setAdjustStatus("0");
            swCkDiffAfterClear.setDeptId(user.getDeptId());
            swCkDiffAfterClear.setCreatorId(user.getId());
            swCkDiffAfterClear.setCreatorName(user.getNikeName());
            list.add(swCkDiffAfterClear);
        }
        swCkDiffAfterClearService.saveBatch(list);
    }

    public Boolean genReport(String startDate, String endDate) {
        boolean flag = false;
        //获取时间段内的日报表数据列表,//TODO 只计算了西安地铁运营商的的数据   20210721 增加机场线和9号线的日报表查询
        List<Map<String,Object>> dailyReportDataList = new ArrayList<>();
        List<Map<String,Object>> dailyReportDataListInit = this.baseMapper.selectDailyReportDataList(startDate,endDate);//西安地铁
        List<Map<String,Object>> dailyReportAirDataList = this.baseMapper.selectOtherOperatorsDailyReportDataList(startDate,endDate);  //机场线
        List<Map<String,Object>> dailyReport9DataList = this.baseMapper.selectOtherXaztOperatorsDailyReportDataList(startDate,endDate);//9号线
        if(CollectionUtil.isNotEmpty(dailyReportAirDataList)){
            dailyReportDataListInit.addAll(dailyReportAirDataList);
        }
        if(CollectionUtil.isNotEmpty(dailyReportAirDataList)){
            dailyReportDataListInit.addAll(dailyReport9DataList);
        }
        if(CollectionUtil.isNotEmpty(dailyReportDataListInit) && dailyReportDataListInit.size()>0){
            Map<String, List<Map<String, Object>>> tradeDateMap = dailyReportDataListInit.stream().collect(Collectors.groupingBy(x -> x.get("tradeDate").toString(), Collectors.toList()));
            Set<String> keySet = tradeDateMap.keySet();
            for (String tradeDate : keySet) {
                Map<String,Object> map = new HashMap<>();
                List<Map<String, Object>> mapsList = tradeDateMap.get(tradeDate);

                BigDecimal a1 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("A1")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal a2 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("A2")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal a3 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("A3")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal a4 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("A4")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal b1 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("B1")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal b2 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("B2")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal e2 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("E2")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal f2 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("F2")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal d1 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("D1")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal d2 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("D2")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal d3 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("D3")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal g1 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("G1")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal g2 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("G2")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal g3 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("G3")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal g8 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("G8")))).reduce(BigDecimal.ZERO,BigDecimal::add);
				BigDecimal g10 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("G10")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                BigDecimal h1 = mapsList.stream().map(m -> new BigDecimal(String.valueOf(m.get("H1")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                map.put("tradeDate",tradeDate);
                map.put("A1",a1);
                map.put("A2",a2);
                map.put("A3",a3);
                map.put("A4",a4);
                map.put("B1",b1);
                map.put("B2",b2);
                map.put("E2",e2);
                map.put("F2",f2);
                map.put("D1",d1);
                map.put("D2",d2);
                map.put("D3",d3);
                map.put("G1",g1);
                map.put("G2",g2);
                map.put("G3",g3);
                map.put("G8",g8);
				map.put("G10",g10);
                map.put("H1",h1);
                dailyReportDataList.add(map);
            }
        }
        List<Map<String,Object>> listB3 = this.baseMapper.getB3(startDate,endDate);
        List<Map<String,Object>> listB4 = this.baseMapper.getB4(startDate,endDate);
        List<Map<String,Object>> listB5 = this.baseMapper.getB5(startDate,endDate);
        List<Map<String,Object>> listB6 = this.baseMapper.getB6(startDate,endDate);
        /*
		List<Map<String,Object>> listC1 = this.baseMapper.getC1(startDate,endDate);
        List<Map<String,Object>> listC2 = this.baseMapper.getC2(startDate,endDate);
        List<Map<String,Object>> listC3 = this.baseMapper.getC3(startDate,endDate);
        List<Map<String,Object>> listC4 = this.baseMapper.getC4(startDate,endDate);
        List<Map<String,Object>> listC5 = this.baseMapper.getC5(startDate,endDate);
        List<Map<String,Object>> listG4 = this.baseMapper.getG4(startDate,endDate);
        List<Map<String,Object>> listG5 = this.baseMapper.getG5(startDate,endDate);
        List<Map<String,Object>> listG6 = this.baseMapper.getG6(startDate,endDate);
        List<Map<String,Object>> listG7 = this.baseMapper.getG7(startDate,endDate);
		List<Map<String,Object>> listG9 = this.baseMapper.getG9(startDate,endDate);
        List<Map<String,Object>> listH2 = this.baseMapper.getH2(startDate,endDate);
		*/
		List<Map<String,Object>> listSystemClearData = this.baseMapper.getSystemClearData(startDate,endDate);

        if (dailyReportDataList != null && !dailyReportDataList.isEmpty()) {

            //插入数据库
            PigxUser user = SecurityUtils.getUser();
            List<SwCkClearingReportOnewayTicket> listSwCkClearingReportOnewayTicket = new ArrayList<>();
            List<SwCkClearingReportQr> listSwCkClearingReportQr = new ArrayList<>();
            List<SwCkClearingAccountRepportFace> listSwCkClearingAccountRepportFace = new ArrayList<>();

            int clearingTimeLimit = swCkClearingTransferDiffReasonService.getClearingTimeLimit();

            for (Map<String,Object> dailyReportMap : dailyReportDataList) {
                String tradeDate = (String)dailyReportMap.get("tradeDate");
                BigDecimal A1 = new BigDecimal(String.valueOf(dailyReportMap.get("A1")));
                BigDecimal A2 = new BigDecimal(String.valueOf(dailyReportMap.get("A2")));
                BigDecimal A3 = new BigDecimal(String.valueOf(dailyReportMap.get("A3")));
                BigDecimal A4 = new BigDecimal(String.valueOf(dailyReportMap.get("A4")));
                BigDecimal A0 = A1.add(A2).add(A3).add(A4);

                BigDecimal B1 = new BigDecimal(String.valueOf(dailyReportMap.get("B1")));
                BigDecimal B2 = new BigDecimal(String.valueOf(dailyReportMap.get("B2")));
                BigDecimal B3 = getLongValue(listB3,tradeDate);
                BigDecimal B4 = getLongValue(listB4,tradeDate);
                BigDecimal B5 = getLongValue(listB5,tradeDate);
                BigDecimal B6 = getLongValue(listB6,tradeDate);
                //Long B0 = B1 + B2 + B3 + B4 - B5 - B6;
                BigDecimal B0 = B1.add(B2).add(B3).add(B4).subtract(B5).subtract(B6);
                /*
                Long C1 = getLongValue(listC1,tradeDate);
                Long C2 = getLongValue(listC2,tradeDate);
                Long C3 = getLongValue(listC3,tradeDate);
                Long C4 = getLongValue(listC4,tradeDate);
                Long C5 = getLongValue(listC5,tradeDate);
                Long C6 = C1 + C2 + C3 + C4 + C5;
				*/

                BigDecimal G1 = new BigDecimal(String.valueOf(dailyReportMap.get("G1")));
                BigDecimal G2 = new BigDecimal(String.valueOf(dailyReportMap.get("G2")));
                BigDecimal G3 = new BigDecimal(String.valueOf(dailyReportMap.get("G3")));
                BigDecimal G8 = new BigDecimal(String.valueOf(dailyReportMap.get("G8"))); //智码APP代售
				BigDecimal G10 = new BigDecimal(String.valueOf(dailyReportMap.get("G10"))); //应急及互联互通
                /*
                Long G4 = getLongValue(listG4,tradeDate);
                Long G5 = getLongValue(listG5,tradeDate);
                Long G6 = getLongValue(listG6,tradeDate);
                Long G7 = getLongValue(listG7,tradeDate);
				Long G9 = getLongValue(listG9,tradeDate);
                Long H1 = (Long)dailyReportMap.get("H1");
                Long H2 = getLongValue(listH2,tradeDate);
				*/
                BigDecimal H1 = new BigDecimal(String.valueOf(dailyReportMap.get("H1")));

                //单程票-实收-应收-应付差异统计表
                SwCkClearingReportOnewayTicket swCkClearingReportOnewayTicket = new SwCkClearingReportOnewayTicket();
                swCkClearingReportOnewayTicket.setTradeDate(LocalDate.parse(tradeDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                //判断是否存在
//                if(swCkClearingReportOnewayTicketService.count(Wrappers.query(swCkClearingReportOnewayTicket)) > 0){
//                    continue;// TODO 调整存在就修改，不存在就新增
//                }
                List<SwCkClearingReportOnewayTicket> listOneway = swCkClearingReportOnewayTicketService.list(Wrappers.query(swCkClearingReportOnewayTicket));
                if(CollectionUtil.isNotEmpty(listOneway)){
                    SwCkClearingReportOnewayTicket ckClearingReportOnewayTicket = listOneway.get(0);
                    swCkClearingReportOnewayTicket.setId(ckClearingReportOnewayTicket.getId());
                }
                swCkClearingReportOnewayTicket.setRealIncomeMoney(A0);
                swCkClearingReportOnewayTicket.setAccReceivableMoney(B0);
				//swCkClearingReportOnewayTicket.setAccPayableMoney(C6);
				swCkClearingReportOnewayTicket.setAccPayableMoney(getSystemClearLongValue(listSystemClearData,tradeDate,"oneway"));
               
                swCkClearingReportOnewayTicket.setDiffAccRealMoney(A0.subtract(B0));
                //swCkClearingReportOnewayTicket.setDiffAccReceivableMoney(B0 - C6);
				swCkClearingReportOnewayTicket.setDiffAccReceivableMoney(swCkClearingReportOnewayTicket.getAccReceivableMoney().subtract(swCkClearingReportOnewayTicket.getAccPayableMoney()));
                swCkClearingReportOnewayTicket.setReplyLimit(clearingTimeLimit);
                swCkClearingReportOnewayTicket.setSendStatus(0);
                swCkClearingReportOnewayTicket.setDeptId(user.getDeptId());
                swCkClearingReportOnewayTicket.setCreatorId(user.getId());
                swCkClearingReportOnewayTicket.setCreatorName(user.getNikeName());
                listSwCkClearingReportOnewayTicket.add(swCkClearingReportOnewayTicket);

                //二维码应收应付差异统计表
                SwCkClearingReportQr swCkClearingReportQr = new SwCkClearingReportQr();
                swCkClearingReportQr.setTradeDate(LocalDate.parse(tradeDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                //判断是否存在
//                if(swCkClearingReportQrService.count(Wrappers.query(swCkClearingReportQr)) > 0){
//                    continue;
//                }
                List<SwCkClearingReportQr> listQr = swCkClearingReportQrService.list(Wrappers.query(swCkClearingReportQr));
                if(CollectionUtil.isNotEmpty(listQr)){
                    SwCkClearingReportQr ckClearingReportQr = listQr.get(0);
                    swCkClearingReportQr.setId(ckClearingReportQr.getId());
                }
                swCkClearingReportQr.setRealIncomeMoney(G1.add(G2).add(G3).add(G8).add(G10));//TODO 是否包括应急及互联互通G10 待定  2021-11-08
                //swCkClearingReportQr.setAccMoney(G4 + G5 + G6 + G7 +G9);
				swCkClearingReportQr.setAccMoney(getSystemClearLongValue(listSystemClearData,tradeDate,"qr"));//TODO 是否包括应急及互联互通G10 待定  2021-11-08
               // swCkClearingReportQr.setDiffAccMoney(swCkClearingReportQr.getAccMoney().subtract(swCkClearingReportQr.getRealIncomeMoney()));2021-12-10 实收-应收
				swCkClearingReportQr.setDiffAccMoney(swCkClearingReportQr.getRealIncomeMoney().subtract(swCkClearingReportQr.getAccMoney()));
                swCkClearingReportQr.setReplyLimit(clearingTimeLimit);
                swCkClearingReportQr.setSendStatus(0);
                swCkClearingReportQr.setDeptId(user.getDeptId());
                swCkClearingReportQr.setCreatorId(user.getId());
                swCkClearingReportQr.setCreatorName(user.getNikeName());
                listSwCkClearingReportQr.add(swCkClearingReportQr);

                //人脸电子票应收应付差异统计表
                SwCkClearingAccountRepportFace swCkClearingAccountRepportFace = new SwCkClearingAccountRepportFace();
                swCkClearingAccountRepportFace.setTradeDate(LocalDate.parse(tradeDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                //判断是否存在
//                if(swCkClearingAccountRepportFaceService.count(Wrappers.query(swCkClearingAccountRepportFace)) > 0){
//                    continue;
//                }
                List<SwCkClearingAccountRepportFace> listFace = swCkClearingAccountRepportFaceService.list(Wrappers.query(swCkClearingAccountRepportFace));
                if(CollectionUtil.isNotEmpty(listFace)){
                    SwCkClearingAccountRepportFace ckClearingAccountRepportFace = listFace.get(0);
                    swCkClearingAccountRepportFace.setId(ckClearingAccountRepportFace.getId());
                }
                swCkClearingAccountRepportFace.setRealIncomeMoney(H1);
                //swCkClearingAccountRepportFace.setAccMoney(H2);
				swCkClearingAccountRepportFace.setAccMoney(getSystemClearLongValue(listSystemClearData,tradeDate,"face"));  //人脸系统清分数据
                //swCkClearingAccountRepportFace.setDiffAccMoney(swCkClearingAccountRepportFace.getAccMoney().subtract(swCkClearingAccountRepportFace.getRealIncomeMoney()));  2021-12-10 实收-应收
				swCkClearingAccountRepportFace.setDiffAccMoney(swCkClearingAccountRepportFace.getRealIncomeMoney().subtract(swCkClearingAccountRepportFace.getAccMoney()));
                swCkClearingAccountRepportFace.setReplyLimit(clearingTimeLimit);
                swCkClearingAccountRepportFace.setSendStatus(0);
                swCkClearingAccountRepportFace.setDeptId(user.getDeptId());
                swCkClearingAccountRepportFace.setCreatorId(user.getId());
                swCkClearingAccountRepportFace.setCreatorName(user.getNikeName());
                listSwCkClearingAccountRepportFace.add(swCkClearingAccountRepportFace);

            }

            if(listSwCkClearingReportOnewayTicket != null && !listSwCkClearingReportOnewayTicket.isEmpty()){
                swCkClearingReportOnewayTicketService.saveOrUpdateBatch(listSwCkClearingReportOnewayTicket);
                flag  = true;
            }
            if(listSwCkClearingReportQr != null && !listSwCkClearingReportQr.isEmpty()) {
                swCkClearingReportQrService.saveOrUpdateBatch(listSwCkClearingReportQr);
                flag  = true;
            }

            if(listSwCkClearingAccountRepportFace != null && !listSwCkClearingAccountRepportFace.isEmpty()) {
                swCkClearingAccountRepportFaceService.saveOrUpdateBatch(listSwCkClearingAccountRepportFace);
                flag  = true;
            }
        }
        return flag;
    }
    //生成月度报表
	public Boolean autoClearMonth(String startDate, String endDate){
		/*1.根据开始日期和结束日期，查询清分对账明细汇总表
		    开始日期是>=startDate
			结束日期<=endDate
			删除标识是0
			
			上述三个条件返回结果，比如返回 4条（4周）记录
			将返回的4条件记录，涉及到金额的进行累加，  运营商、线路等直接取其中的一个值      系统清分比例先计算合计然后除以4
            将上述4条记录合成一个记录，插入或者更新到清分对账明细汇总表内

			同时生成主表的swCkClearDetail 数据

           2.将新生成的整月的这条记录，同时更新清分后数据差异表内。

		*/
        //生成之前先删除主子表之前生成过1-31号的数据
        this.remove(Wrappers.<SwCkClearDetail>lambdaQuery().eq(SwCkClearDetail::getBeginTime,startDate).eq(SwCkClearDetail::getEndTime,endDate));
        swCkClearAccountDetailService.remove(Wrappers.<SwCkClearAccountDetail>lambdaQuery().eq(SwCkClearAccountDetail::getBeginTime,startDate).eq(SwCkClearAccountDetail::getEndTime,endDate));
        PigxUser user = SecurityUtils.getUser();
        //主表按各个线路计算合计
        List<SwCkClearDetail> clearDetailList = this.baseMapper.listQuery(startDate,endDate);
        //子表按 线路计算合计
        List<SwCkClearAccountDetail> clearAccountDetailList = swCkClearAccountDetailService.listQueryAccountDetail(startDate,endDate);

        //组织主子表数据
        if(CollectionUtil.isNotEmpty(clearDetailList)){
            for (SwCkClearDetail swCkClearDetail : clearDetailList) {
                String uuid = UUID.randomUUID().toString().toLowerCase();
                swCkClearDetail.setUuid(uuid);
                swCkClearDetail.setDeptId(user.getDeptId());
                swCkClearDetail.setCreatorId(user.getId());
                swCkClearDetail.setCreatorName(user.getNikeName());
                swCkClearDetail.setDelFlag("0");
                if(CollectionUtil.isNotEmpty(clearAccountDetailList)){
                    for (SwCkClearAccountDetail swCkClearAccountDetail : clearAccountDetailList) {
                        if(swCkClearDetail.getLineCode().equals(swCkClearAccountDetail.getLineCode())){
                            swCkClearAccountDetail.setRalationId(uuid);
                            swCkClearAccountDetail.setDeptId(user.getDeptId());
                            swCkClearAccountDetail.setCreatorId(user.getId());
                            swCkClearAccountDetail.setCreatorName(user.getNikeName());
                            swCkClearAccountDetail.setDelFlag("0");
                            break;
                        }
                    }
                }
            }

            //主表判断是否存在，存在更新，不存在insert
            List<SwCkClearDetail> ckClearDetailListOld = this.baseMapper.selectList(Wrappers.<SwCkClearDetail>lambdaQuery()
                    .eq(SwCkClearDetail::getBeginTime, startDate)
                    .eq(SwCkClearDetail::getEndTime, endDate)
                    .eq(SwCkClearDetail::getDelFlag, "0"));
            List<SwCkClearDetail> collectClearDetail = clearDetailList.stream().map(m -> {
                ckClearDetailListOld.stream().filter(m2 -> m.getLineCode().equals(m2.getLineCode()))
                        .forEach(s -> {
                            m.setId(s.getId());
                            m.setUuid(s.getUuid());
                            m.setUpdateTime(LocalDateTime.now());
                        });
                return m;
            }).collect(Collectors.toList());
            this.saveOrUpdateBatch(collectClearDetail);
            //子表判断是否存在，存在更新，不存在insert
            List<SwCkClearAccountDetail> clearAccountDetailListOld = swCkClearAccountDetailService.list(Wrappers.<SwCkClearAccountDetail>lambdaQuery()
                    .eq(SwCkClearAccountDetail::getBeginTime, startDate)
                    .eq(SwCkClearAccountDetail::getEndTime, endDate)
                    .eq(SwCkClearAccountDetail::getDelFlag, "0"));
            List<SwCkClearAccountDetail> collectClearAccountDetail = clearAccountDetailList.stream().map(m -> {
                clearAccountDetailListOld.stream().filter(m2 -> m.getLineCode().equals(m2.getLineCode()))
                        .forEach(s -> {
                            m.setId(s.getId());
                            m.setRalationId(s.getRalationId());
                            m.setUpdateTime(LocalDateTime.now());
                        });
                return m;
            }).collect(Collectors.toList());
            swCkClearAccountDetailService.saveOrUpdateBatch(collectClearAccountDetail);
            //2.将新生成的整月的这条记录，同时更新清分后数据差异表内。
            //生成清分后数据差异表处理
            createSwCkDiffAfterClear(startDate,endDate);
            return true;
        }
        return false;
		
	}

    private BigDecimal getLongValue( List<Map<String,Object>> listMap,String tradeDate) {
        if(listMap == null || listMap.isEmpty()){
            return new BigDecimal("0");
        }
        for (Map<String,Object> map : listMap){
            if(tradeDate.equals(map.get("tradeDate"))) {
                return new BigDecimal(String.valueOf(map.get("longValue")));
            }
        }
        return new BigDecimal("0");
    }
	//获取系统清分数据，根据日期
	private BigDecimal getSystemClearLongValue( List<Map<String,Object>> listMap,String tradeDate,String key) {
        if(listMap == null || listMap.isEmpty()){
            return new  BigDecimal("0");
        }
        for (Map<String,Object> map : listMap){
            if(tradeDate.equals(map.get("tradeDate"))) {
                return new BigDecimal(String.valueOf(map.get(key)));
            }
        }
        return new  BigDecimal("0");
    }
	//获取系统清分数据,根据线路
	private BigDecimal getSystemClearLongValueByLineCode( List<Map<String,Object>> listMap,String lineCode,String key) {
        if(listMap == null || listMap.isEmpty()){
            return new  BigDecimal("0");
        }
        for (Map<String,Object> map : listMap){
            if(lineCode.equals(map.get("lineCode"))) {
                return new BigDecimal(String.valueOf(map.get(key)));
            }
        }
        return new  BigDecimal("0");
    }
	//根据线路编号获取线路名称
	private String getLineName (List<Map<String,String>> lineMap,String lineCode) {
	   for (Map<String,String> map : lineMap){
	            if(lineCode.equals(map.get("CODE"))){
	                return map.get("NAME");
	            }
	        }
	        return "";
	 }

    private BigDecimal getData(BigDecimal money){
        try {
            if(money == null){
                return new  BigDecimal("0");
            }
            return money;

        } catch (Exception e) {
            return new  BigDecimal("0");
        }

    }

    private String getData2(String money){
        try {
            if(money == null){
                return "0.00";
            }
            return money;

        } catch (Exception e) {
            return "0.00";
        }

    }
}
